原题:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
解决方案:
由于给出的数就是倒序的,也就是从个位开始的,所以很容易就可以计算出他们的和,唯一要注意的是最后的进位不要忘了加上。
代码:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* res = NULL, *cur=NULL;
int remaining = 0;
while(l1 || l2){
remaining += (l1 ? l1->val : 0) + (l2 ? l2->val : 0);
ListNode* node= new ListNode(remaining % 10);
remaining /= 10;
if (!res)
res = node;
if (cur)
cur->next = node;
cur = node;
if (l1)
l1 = l1->next;
if (l2)
l2 = l2->next;
}
if (remaining > 0){
ListNode* node= new ListNode(remaining);
cur->next = node;
}
return res;
}