forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
add-two-numbers-ii.cpp
51 lines (45 loc) · 1.12 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
// Time: O(m + n)
// Space: O(m + n)
/**
* 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) {
stack<int> stk1, stk2;
while (l1) {
stk1.emplace(l1->val);
l1 = l1->next;
}
while (l2) {
stk2.emplace(l2->val);
l2 = l2->next;
}
ListNode *prev = nullptr, *head = nullptr;
int sum = 0;
while (!stk1.empty() || !stk2.empty()) {
sum /= 10;
if (!stk1.empty()) {
sum += stk1.top();
stk1.pop();
}
if (!stk2.empty()) {
sum += stk2.top();
stk2.pop();
}
head = new ListNode(sum % 10);
head->next = prev;
prev = head;
}
if (sum >= 10) {
head = new ListNode(sum / 10);
head->next = prev;
}
return head;
}
};