-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd two numbers represented by linked lists
77 lines (66 loc) · 1.36 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
/* node for linked list:
struct Node {
int data;
struct Node* next;
Node(int x) {
data = x;
next = NULL;
}
};
*/
Node* reverse(Node *head)
{
Node *curr = head;
Node *next = NULL;
Node *prev = NULL;
while(curr)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
void addBack(Node *&head, Node *&last, int data){
Node *newNode=new Node(data);
// newNode->data=data;
newNode->next=NULL;
if(last==NULL){
head=newNode;
}
else{
last->next=newNode;
}
last=newNode;
}
struct Node* addTwoLists(struct Node* first, struct Node* second)
{
Node *head1=reverse(first);
Node *head2=reverse(second);
Node *res;
Node *last=NULL; // Last node of new list
int total,carry=0;
// One of them not NULL
while(head1|| head2){
int a=(head1)?(head1->data):(0); // If NULL contri is 0
int b=(head2)?(head2->data):(0);
total=(a+b+carry);
carry=(total/10);
total=total%10;
// Add this to back of new list
addBack(res,last,total);
if(head1){
head1=head1->next;
}
if(head2){
head2=head2->next;
}
}
if(carry!=0){
addBack(res,last,carry);
}
res = reverse(res);
return res;
}