1. 用carry來每次更新進位.
2. 考慮特殊情況, [0,1]和[0,1,2], []和[0,1], [1]和[9,9], 即額外的進位.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
//啞結點,初始化返回的鏈表的第一個節點.
ListNode* dummy = new ListNode(0);
ListNode* cur = dummy;
int carry = 0;
int value1 = 0, value2 = 0;
while(l1!=NULL || l2!=NULL) {
//鏈表可能不一樣長.
value1 = (l1==NULL) ? 0:l1->val;
value2 = (l2==NULL) ? 0:l2->val;
int sum = value1+value2+carry;
carry = sum/10;
cur->next = new ListNode(sum%10);
cur = cur->next;
if(l1!=NULL) l1 = l1->next;
if(l2!=NULL) l2 = l2->next;
}
//鏈表最後可能有進位.
if(carry>0) cur->next = new ListNode(carry);
return dummy->next;
}
};