-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd two numbers represented by linked lists
94 lines (89 loc) Β· 2.95 KB
/
Add two numbers represented by linked lists
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
class Solution
{
public:
//Function to reverse the linked list
struct Node* reverse(struct Node* head){
struct Node* temp = head;
struct Node* nxt = head;
struct Node* prev = NULL;
while(temp!=NULL){
nxt = temp->next;
temp->next = prev;
prev = temp;
temp = nxt;
}
return prev;
}
struct Node* addTwoLists(struct Node* num1, struct Node* num2)
{
// removing the non - significant zeros
struct Node* t1 = num1;
struct Node* t2 = num2;
while(t1!=NULL and t1->data==0){
t1 = t1->next;
}
while(t2!=NULL and t2->data==0){
t2 = t2->next;
}
// edge case
if(t1==NULL) return (t2==NULL)? new struct Node(0) : t2;
if(t2==NULL) return (t1==NULL)? new struct Node(0) : t1;
// reverse the numbers
struct Node* revnum1 = reverse(t1);
struct Node* revnum2 = reverse(t2);
// new linked list to store the answer
struct Node* dummy = new struct Node(-1);
struct Node* ptr = dummy;
struct Node* temp1 = revnum1;
struct Node* temp2 = revnum2;
int carry = 0;
while(temp1!=NULL && temp2!=NULL){
int val = carry + temp1->data + temp2->data;
if(val>9) carry = 1;
else carry = 0;
val = val%10;
struct Node* temp = new struct Node(val);
ptr->next = temp;
ptr = ptr->next;
temp1 = temp1->next;
temp2 = temp2->next;
}
// if num2 > num1, to add the remaining digits;
if(temp1==NULL){
if(carry == 0) ptr->next = temp2;
else{
while(temp2!=NULL){
int val = carry + temp2->data;
if(val>9) carry = 1;
else carry = 0;
val = val%10;
struct Node* temp = new struct Node(val);
ptr->next = temp;
ptr = ptr->next;
temp2 = temp2->next;
}
//if there is still a carry at the end
if(carry == 1) ptr->next = new struct Node(1);
}
}
if(temp2 == NULL){
if(carry == 0) ptr->next = temp1;
else{
while(temp1!=NULL){
int val = carry + temp1->data;
if(val>9) carry = 1;
else carry = 0;
val = val%10;
struct Node* temp = new struct Node(val);
ptr->next = temp;
ptr = ptr->next;
temp1 = temp1->next;
}
// if there is still a carry at the end
if(carry == 1) ptr->next = new struct Node(1);
}
}
// return the reverse
return reverse(dummy->next);
}
};