Skip to content

Commit 97e09b6

Browse files
authored
Create 445. Add Two Numbers II
Linked list
1 parent 12c893e commit 97e09b6

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

Diff for: 445. Add Two Numbers II

+97
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* reverse(ListNode* head)
14+
{
15+
ListNode* curr = head;
16+
ListNode* prev = NULL;
17+
ListNode* Next = NULL;
18+
19+
while(curr != NULL)
20+
{
21+
Next = curr -> next;
22+
curr -> next = prev;
23+
prev = curr;
24+
curr = Next;
25+
}
26+
27+
return prev;
28+
}
29+
void insertAtTail(ListNode* &head, ListNode* &tail, int d)
30+
{
31+
ListNode* temp = new ListNode(d);
32+
33+
if(head == NULL)
34+
{
35+
head = temp;
36+
tail = temp;
37+
}
38+
else
39+
{
40+
tail -> next = temp;
41+
tail = temp;
42+
}
43+
}
44+
45+
ListNode* add(ListNode* first, ListNode* second)
46+
{
47+
if(first == NULL)
48+
return second;
49+
if(second == NULL)
50+
return first;
51+
52+
ListNode* ansHead = NULL;
53+
ListNode* ansTail = NULL;
54+
int carry = 0;
55+
56+
while(first != NULL || second != NULL || carry != 0)
57+
{
58+
int val1 = 0, val2 = 0;
59+
if(first != NULL)
60+
val1 = first -> val;
61+
if(second != NULL)
62+
val2 = second -> val;
63+
64+
int sum = val1 + val2 + carry;
65+
int digit = sum % 10;
66+
67+
insertAtTail(ansHead, ansTail, digit);
68+
69+
carry = sum / 10;
70+
71+
if(first != NULL)
72+
first = first -> next;
73+
if(second != NULL)
74+
second = second -> next;
75+
}
76+
77+
return ansHead;
78+
}
79+
80+
81+
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
82+
//reverse the given linked lists
83+
l1 = reverse(l1);
84+
l2 = reverse(l2);
85+
86+
//add from left
87+
ListNode* ans = add(l1, l2);
88+
89+
90+
//revert the ans
91+
ans = reverse(ans);
92+
93+
94+
return ans;
95+
96+
}
97+
};

0 commit comments

Comments
 (0)