熟悉指针的用法。要先虚拟出一个头指针,但是用二级指针应该可以回避这个问题。
/**
* 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) {
if(!l1 || !l2){
return l1 ? l1 : l2;
}
ListNode *ans = new ListNode(0);
ListNode *cur1 = l1, *cur2 = l2, *head = ans;
int carry = 0;
int sum, n1, n2;
while(cur1 || cur2){
n1 = cur1 ? cur1->val : 0;
n2 = cur2 ? cur2->val : 0;
sum = (n1 + n2 + carry) % 10;
carry = (n1 + n2 + carry) / 10;
ans->next = new ListNode(sum);
cur1 = cur1 ? cur1->next : NULL;
cur2 = cur2 ? cur2->next : NULL;
ans = ans->next;
}
if(carry){
ans->next = new ListNode(1);
}
return head->next;
}
};