forked from Nanduag0/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAddTwoNumbersRepresentedByLinkedList_Geeks.txt
60 lines (57 loc) · 1.4 KB
/
AddTwoNumbersRepresentedByLinkedList_Geeks.txt
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
class Solution
{
public:
//Function to add two numbers represented by linked list.
struct Node* addTwoLists(struct Node* first, struct Node* second)
{
//code here
int carry=0,sum=0;
Node *temp;
Node* head1=reverse(first);
Node* head2=reverse(second);
Node* head3 = addtwonumbers(head1,head2);
return reverse(head3);
}
struct Node* addtwonumbers(struct Node* first,struct Node* second)
{
Node *res=NULL;
int sum =0;
int carry=0;
Node *pre=NULL;
Node *temp;
while(first!=NULL || second!=NULL)
{
sum=carry+(first?first->data:0)+(second?second->data:0);
carry=(sum>=10)?1:0;
sum=sum%10;
temp=new Node(sum%10);
if(res==NULL)
res=temp;
else
pre->next=temp;
pre=temp;
if(first)
first=first->next;
if(second)
second=second->next;
}
if(carry)
temp->next=new Node(carry);
return res;
}
struct Node* reverse(struct Node* head)
{
Node* pre=NULL;
Node* next;
Node* current=head;
while(current!=NULL)
{
next=current->next;
current->next=pre;
pre=current;
current=next;
}
head=pre;
return head;
}
};