标签:|| val add public tco space 求和 new lis
一:解题思路
这个题目和上一道二进制求和题目类似。Time:O(max(m,n)),Space:O(n)
二:完整代码示例 (C++版和Java版)
C++:
class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* dummy = new ListNode(0); ListNode*p = dummy; int carry = 0; while (l1 != NULL || l2 != NULL || carry != 0) { int sum = carry; if (l1 != NULL) { sum += l1->val; l1 = l1->next; } if (l2 != NULL) { sum+=l2->val; l2 = l2->next; } p->next = new ListNode(sum%10); p = p->next; carry = sum / 10; } return dummy->next; } };
Java:
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummy=new ListNode(0); ListNode p=dummy; int carry=0; while(l1!=null || l2!=null || carry!=0) { int sum=carry; if(l1!=null) { sum+=l1.val; l1=l1.next; } if(l2!=null) { sum+=l2.val; l2=l2.next; } p.next=new ListNode(sum%10); p=p.next; carry=sum/10; } return dummy.next; } }
标签:|| val add public tco space 求和 new lis
原文地址:https://www.cnblogs.com/repinkply/p/12634433.html