-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path445.cpp
33 lines (33 loc) · 801 Bytes
/
445.cpp
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
// vector.cpp
/**
* 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) {
vector<int> arr1, arr2;
while (l1) {
arr1.emplace_back(l1->val);
l1 = l1->next;
}
while (l2) {
arr2.emplace_back(l2->val);
l2 = l2->next;
}
ListNode *p = new ListNode(0);
int i, j, c = 0, val;
for (i = arr1.size() - 1, j = arr2.size() - 1; i >= 0 || j >= 0 || c > 0;
c = val / 10) {
val = (i >= 0 ? arr1[i--] : 0) + (j >= 0 ? arr2[j--] : 0) + c;
ListNode *node = new ListNode(val % 10);
node->next = p->next;
p->next = node;
}
return p->next;
}
};