-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddTwoNumbersII.cpp
More file actions
42 lines (41 loc) · 1.13 KB
/
addTwoNumbersII.cpp
File metadata and controls
42 lines (41 loc) · 1.13 KB
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
// Source: https://leetcode.com/problems/add-two-numbers-ii/
// Author: Miao Zhang
// Date: 2021-02-12
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> st1;
stack<int> st2;
while (l1) {
st1.push(l1->val);
l1 = l1->next;
}
while (l2) {
st2.push(l2->val);
l2 = l2->next;
}
ListNode* head = nullptr;
int carry = 0;
while (!st1.empty() || !st2.empty() || carry) {
carry += st1.empty() ? 0 : st1.top();
carry += st2.empty() ? 0 : st2.top();
if (!st1.empty()) st1.pop();
if (!st2.empty()) st2.pop();
ListNode* node = new ListNode(carry % 10);
carry /= 10;
node->next = head;
head = node;
}
return head;
}
};