-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd_two_numbers_represented_by_linked_lists.cpp
66 lines (52 loc) · 1.45 KB
/
Add_two_numbers_represented_by_linked_lists.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
/*struct Node {
int data;
struct Node* next;
Node(int x) {
data = x;
next = NULL;
}
};
*/
class Solution
{
public:
//Function to add two numbers represented by linked list.
Node* trimZero(Node* head){
Node* cur = head;
while(cur != NULL && cur->data == 0){
cur = cur->next;
}
return cur;
}
Node* reverse(Node* head){
Node* cur = head;
Node* prev = NULL;
while(cur != NULL){
Node* next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
struct Node* addTwoLists(struct Node* num1, struct Node* num2)
{
num1 = reverse(trimZero(num1));
num2 = reverse(trimZero(num2));
if(num1 == NULL && num2 == NULL)return new Node(0);
Node* head = new Node(-1);
Node* tail = head;
int carry = 0;
while(num1 != NULL || num2 != NULL || carry != 0){
int x = num1 == NULL ? 0 : num1->data;
int y = num2 == NULL ? 0 : num2->data;
int d = x+y+carry;
carry = d/10;
tail->next = new Node(d%10);
tail = tail->next;
if(num1 != NULL)num1 = num1->next;
if(num2 != NULL)num2 = num2->next;
}
return reverse(head->next);
}
};