-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoNumbersII2.cpp
More file actions
91 lines (74 loc) · 1.44 KB
/
AddTwoNumbersII2.cpp
File metadata and controls
91 lines (74 loc) · 1.44 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include<iostream>
#include<stack>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> s1, s2;
ListNode *p = l1;
while(p) {
s1.push(p->val);
p = p->next;
}
p = l2;
while(p) {
s2.push(p->val);
p = p->next;
}
ListNode *result = new ListNode(0);
int carry = 0;
while(!s1.empty() || !s2.empty()) {
int num1 = 0, num2 = 0;
if(!s1.empty()) {
num1 = s1.top();
s1.pop();
}
if(!s2.empty()) {
num2 = s2.top();
s2.pop();
}
carry += num1 + num2;
result->val = carry % 10;
ListNode* q = new ListNode(carry / 10);
q->next = result;
result = q;
carry /= 10;
}
return result->val == 0 ? result->next : result;
}
};
int main() {
int n;
cin>>n;
ListNode *head1 = new ListNode(0);
ListNode *p = head1;
for(int i = 0; i < n; i++) {
int num;
cin>>num;
p->next = new ListNode(num);
p = p->next;
}
head1 = head1->next;
cin>>n;
ListNode *head2 = new ListNode(0);
p = head2;
for(int i = 0; i < n; i++) {
int num;
cin>>num;
p->next = new ListNode(num);
p = p->next;
}
head2 = head2->next;
Solution *solution = new Solution();
ListNode *head = solution->addTwoNumbers(head1, head2);
while(head) {
cout<<head->val<<" ";
head = head->next;
}
return 0;
}