-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAddTwoNumbers-II_445.cpp
138 lines (114 loc) · 3.11 KB
/
AddTwoNumbers-II_445.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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/*
~ Author : leetcode.com/tridib_2003/
~ Problem : 445. Add Two Numbers II
~ Link : https://leetcode.com/problems/add-two-numbers-ii/
*/
/**
* 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) {}
* };
*/
// ***** Approach 1 (Iterative) *****
class Solution {
private:
ListNode* insertNode(ListNode *head, int data) {
ListNode *temp = new ListNode(data);
temp -> next = head;
return temp;
}
int getListSize(ListNode *head) {
int size = 0;
while (head) {
++size;
head = head -> next;
}
return size;
}
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (!l1)
return l2;
if (!l2)
return l1;
int len1 = getListSize(l1);
int len2 = getListSize(l2);
ListNode *curr1 = l1, *curr2 = l2, *res = NULL;
while (len1 > 0 && len2 > 0) {
int sum = 0;
if (len1 >= len2) {
sum = curr1 -> val;
curr1 = curr1 -> next;
--len1;
}
if (len2 > len1) {
sum += curr2 -> val;
curr2 = curr2 -> next;
--len2;
}
res = insertNode(res, sum);
}
curr1 = res, res = NULL;
int carry = 0;
while (curr1) {
curr1 -> val += carry;
carry = curr1 -> val / 10;
res = insertNode(res, curr1 -> val % 10);
curr2 = curr1;
curr1 = curr1 -> next;
delete curr2;
}
if (carry)
res = insertNode(res, 1);
return res;
}
};
// ***** Approach 2 (Using Stack) *****
/*
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (!l1) return l2;
if (!l2) return l1;
stack <int> s1, s2;
ListNode *temp = l1;
while (temp) {
s1.push(temp -> val);
temp = temp -> next;
}
temp = l2;
while (temp) {
s2.push(temp -> val);
temp = temp -> next;
}
ListNode *res = NULL;
int carry = 0;
while (!s1.empty() || !s2.empty()) {
int sum = 0;
if (!s1.empty()) {
sum = s1.top();
s1.pop();
}
if (!s2.empty()) {
sum += s2.top();
s2.pop();
}
sum += carry;
ListNode *newNode = new ListNode(sum % 10);
newNode -> next = res;
res = newNode;
carry = sum / 10;
}
if (carry) {
ListNode *newNode = new ListNode(1);
newNode -> next = res;
res = newNode;
}
return res;
}
};
*/