-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2. Add Two Numbers
93 lines (77 loc) · 1.99 KB
/
2. Add Two Numbers
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
/**
* 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* prev = NULL;
ListNode* curr = head;
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 digit)
{
ListNode* temp = new ListNode(digit);
if(head == NULL)
{
head = temp;
tail = temp;
}
else
{
tail -> next = temp;
tail = temp;
}
}
ListNode* add(ListNode* l1, ListNode* l2){
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode* ansHead = NULL;
ListNode* ansTail = NULL;
int carry = 0, sum = 0, digit = 0;
while(l1 != NULL || l2 != NULL || carry != 0)
{
int val1 = 0;
if(l1 != NULL)
val1 = l1 -> val;
int val2 = 0;
if(l2 != NULL)
val2 = l2 -> val;
//find sum
sum = carry + val1 +val2;
//find the digit
digit = sum % 10;
//create node with digit
insertAtTail(ansHead, ansTail, digit);
//find carry
carry = sum / 10;
if(l1 != NULL)
l1 = l1 -> next;
if(l2 != NULL)
l2 = l2 -> next;
}
return ansHead;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
//Step 2. add from left
ListNode* ans = add(l1, l2);
return ans;
}
};