-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add two numbers represented by linked lists.cpp
112 lines (100 loc) · 2.36 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
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
101
102
103
104
105
106
107
108
109
110
111
112
// Time complexity - O(N+M)
// Space complexity- O(max(N,M))
class Solution
{
public:
Node* reverse(Node* root)
{
//base case
if(root==NULL)
return NULL;
if(root->next==NULL)
return root;
//recursive calls
Node* temp=reverse(root->next);
root->next->next=root;
root->next=NULL;
return temp;
}
struct Node* addTwoLists(struct Node* first, struct Node* second)
{
Node* i=reverse(first);
Node* j=reverse(second);
Node* head=NULL;
Node* tail=NULL;
int c=0;
while(i and j)
{
int sum=c+(i->data)+(j->data);
int first=sum/10;
int last=sum%10;
c=first;
Node* newnode=new Node(last);
if(head==NULL)
{
head=newnode;
tail=head;
}
else
{
tail->next=newnode;
tail=newnode;
}
i=i->next;
j=j->next;
}
while(i)
{
int sum=c+i->data;
int first=sum/10;
int last=sum%10;
c=first;
Node* newnode=new Node(last);
if(head==NULL)
{
head=newnode;
tail=head;
}
else
{
tail->next=newnode;
tail=newnode;
}
i=i->next;
}
while(j)
{
int sum=c+j->data;
int first=sum/10;
int last=sum%10;
c=first;
Node* newnode=new Node(last);
if(head==NULL)
{
head=newnode;
tail=head;
}
else
{
tail->next=newnode;
tail=newnode;
}
j=j->next;
}
if(c)
{
Node* newnode=new Node(c);
tail->next=newnode;
tail=newnode;
}
head=reverse(head);
while(head and head->data==0)
head=head->next;
if(!head)
{
Node* newnode=new Node(0);
return newnode;
}
return head;
}
};