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;
}
};