-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.cc
38 lines (37 loc) · 784 Bytes
/
2.cc
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
/**
* 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(0), *pointer = &l3;
int up = 0;
while (l1 || l2) {
pointer->next = new ListNode(pointer->val);
pointer = pointer->next;
pointer->val=0;
if(l1) {
pointer->val+= (l1->val + up);
l1 = l1->next;
up = 0;
}
if(l2) {
pointer->val+= (l2->val + up);
l2 = l2->next;
up= 0;
}
up = pointer->val/10;
pointer->val = pointer->val%10;
}
if (up > 0) {
pointer->next = new ListNode(up);
}
return l3.next;
}
};