https://leetcode.com/problems/add-two-numbers/description/

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.
你可以假设这两个数字不包含任何前导零,除了数字0本身。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* 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) {
int n = l1->val+l2->val;
ListNode *head = new ListNode(n%10);
ListNode *tmp = head;
l1 = l1->next;
l2 = l2->next;

while((l1) && (l2)){
n = n/10;
n = n + l1->val + l2->val;
tmp->next = new ListNode(n%10);
tmp = tmp->next;
l1 = l1->next;
l2 = l2->next;
}
while((l1)){
n = n/10;
n += l1->val;
tmp->next = new ListNode(n%10);
tmp = tmp->next;
l1=l1->next;
}
while((l2)){
n = n/10;
n += l2->val;
tmp->next = new ListNode(n%10);
tmp = tmp->next;
l2=l2->next;
}
if (n/=10){
tmp->next = new ListNode(n);
}

return head;
}
};