- 先声明一个链表指针l1,在声明一个链表指针l2, 用l1来维护他们的和,l2记录l1的初始位置。
/**
* 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* l3 = new ListNode(0);
ListNode* l4 = l3;
int res = 0;
while(l1 || l2){
l3->val += res;
res = 0;
if(l1)
l3->val += l1->val, l1 = l1->next;
if(l2)
l3->val += l2->val, l2 = l2->next;
if(l3->val > 9)
res += (l3->val) / 10, l3->val = (l3->val) % 10;
if((l1 || l2) == false){
if(res != 0){
l3->next = new ListNode(0);
l3 = l3->next;
l3->val += res;
}
break;
}
l3->next = new ListNode(0);
l3 = l3->next;
}
return l4;
}
};