[LeetCode] Add Two Numbers II

445. Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

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
/**
* 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> s1, s2;
while(l1 != nullptr) {
s1.push(l1->val);
l1 = l1->next;
}
while(l2 != nullptr) {
s2.push(l2->val);
l2 = l2->next;
}

ListNode* head = nullptr;
int add = 0;
while(!s1.empty() || !s2.empty()) {
if(!s1.empty()) add += s1.top(), s1.pop();
if(!s2.empty()) add += s2.top(), s2.pop();
head = new ListNode(add % 10, head);
add /= 10;
}


return add ? new ListNode(add, head) : head;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/13/PS/LeetCode/add-two-numbers-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.