-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path445. Add Two Numbers II
97 lines (78 loc) · 2.05 KB
/
445. Add Two Numbers II
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
/**
* 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* reverse(ListNode* head)
{
ListNode* curr = head;
ListNode* prev = NULL;
ListNode* Next = NULL;
while(curr != NULL)
{
Next = curr -> next;
curr -> next = prev;
prev = curr;
curr = Next;
}
return prev;
}
void insertAtTail(ListNode* &head, ListNode* &tail, int d)
{
ListNode* temp = new ListNode(d);
if(head == NULL)
{
head = temp;
tail = temp;
}
else
{
tail -> next = temp;
tail = temp;
}
}
ListNode* add(ListNode* first, ListNode* second)
{
if(first == NULL)
return second;
if(second == NULL)
return first;
ListNode* ansHead = NULL;
ListNode* ansTail = NULL;
int carry = 0;
while(first != NULL || second != NULL || carry != 0)
{
int val1 = 0, val2 = 0;
if(first != NULL)
val1 = first -> val;
if(second != NULL)
val2 = second -> val;
int sum = val1 + val2 + carry;
int digit = sum % 10;
insertAtTail(ansHead, ansTail, digit);
carry = sum / 10;
if(first != NULL)
first = first -> next;
if(second != NULL)
second = second -> next;
}
return ansHead;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
//reverse the given linked lists
l1 = reverse(l1);
l2 = reverse(l2);
//add from left
ListNode* ans = add(l1, l2);
//revert the ans
ans = reverse(ans);
return ans;
}
};