Copy ListNode head(0), * p = &head;
Copy while (l1 || l2 || cast) {
int sum = l1 + l2 + cast;
int value = sum % 10;
int cast = sum / 10;
p->next = new ListNode(value);
p = p->next;
l1 = l1? l1->next : l1;
l2 = l2? l2->next : l2;
}
Copy p = &head;
return head->next
Copy /**
* 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 preHead(0),*p = &preHead;
int extra=0,sum=0;
while( l1 || l2 || extra){
sum= (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra;
extra = sum / 10;
p->next = new ListNode(sum % 10);
p = p->next;
l1 = l1? l1->next : l1;
l2 = l2? l2->next : l2;
}
p = &preHead;
return p->next;
}
};