-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAdd_Two_Numbers_II.cpp
More file actions
100 lines (85 loc) · 2.08 KB
/
Add_Two_Numbers_II.cpp
File metadata and controls
100 lines (85 loc) · 2.08 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
92
93
94
95
96
97
98
99
100
// https://leetcode.com/problems/add-two-numbers-ii/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Node {
public:
unordered_map < ListNode *, ListNode * > mp;
ListNode *tail;
Node(ListNode *head)
{
ListNode *prev = NULL;
while(head != NULL)
{
tail = head;
mp[head] = prev;
prev = head;
head = head->next;
}
}
ListNode *getPrev(ListNode *curr)
{
return mp[curr];
}
ListNode *getTail()
{
return tail;
}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
Node *A = new Node(l1);
Node *B = new Node(l2);
ListNode *f = A->getTail();
ListNode *s = B->getTail();
ListNode *res = NULL;
int carry = 0;
while(f != NULL && s != NULL)
{
int sum = f->val + s->val + carry;
if(res == NULL)
res = new ListNode(sum % 10);
else
{
ListNode *ptr = new ListNode(sum % 10);
ptr->next = res;
res = ptr;
}
carry = sum/10;
f = A->getPrev(f);
s = B->getPrev(s);
}
while(f != NULL)
{
int sum = carry + f->val;
ListNode *ptr = new ListNode(sum % 10);
ptr->next = res;
res = ptr;
carry = sum/10;
f = A->getPrev(f);
}
while(s != NULL)
{
int sum = carry + s->val;
ListNode *ptr = new ListNode(sum % 10);
ptr->next = res;
res = ptr;
carry = sum/10;
s = B->getPrev(s);
}
if(carry)
{
ListNode *ptr = new ListNode(1);
ptr->next = res;
res = ptr;
}
return res;
}
};