-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathadd-two-numbers-ii.cpp
56 lines (52 loc) · 1.14 KB
/
add-two-numbers-ii.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//Runtime: 42 ms
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int>a;
stack<int>b;
while (l1)
{
a.push(l1->val);
l1 = l1->next;
}
while (l2)
{
b.push(l2->val);
l2 = l2->next;
}
int r = 0;
ListNode* res = new ListNode(-1);
ListNode* t = res;
while (!a.empty() || !b.empty())
{
int n = r;
if (!a.empty())
{
n += a.top();
a.pop();
}
if (!b.empty())
{
n += b.top();
b.pop();
}
r = n / 10;
n = n % 10;
res->next = new ListNode(n);
res = res->next;
}
if (r > 0)
res->next = new ListNode(r);
res = t->next;
ListNode* prev = NULL;
ListNode* next;
while (res)
{
next = res->next;
res->next = prev;
prev = res;
res = next;
}
return prev;
}
};