forked from redkirti/Striver-SDE-Sheet-Challenge
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAddTwoNumbersAsLinkedList.cpp
75 lines (71 loc) · 1.68 KB
/
AddTwoNumbersAsLinkedList.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
#include <bits/stdc++.h>
/****************************************************************
Following is the class structure of the Node class:
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
*****************************************************************/
Node *addTwoNumbers(Node *head1, Node *head2)
{
Node *head3 = NULL, *head = head3;
int s=0,r=0;
while(head1!=NULL && head2!=NULL){
s = head1->data+head2->data+r;
head1 = head1->next;
head2 = head2->next;
if(s>9) r = 1;
else r = 0;
Node *temp = new Node(s%10);
if(head3==NULL){
head3 = temp;
head=head3;
}
else{
head3->next = temp;
head3 = head3->next;
}
}
while(head1!=NULL){
s = head1->data+r;
if(s>9) r = 1;
else r = 0;
Node *temp = new Node(s%10);
if(head3==NULL){
head3 = temp;
head=head3;
}
else{
head3->next = temp;
head3 = head3->next;
}
head1=head1->next;
}
while(head2!=NULL){
s = head2->data+r;
if(s>9) r = 1;
else r = 0;
Node *temp = new Node(s%10);
if(head3==NULL){
head3 = temp;
head=head3;
}
else{
head3->next = temp;
head3 = head3->next;
}
head2=head2->next;
}
if(r==1){
Node *temp = new Node(1);
head3->next = temp;
}
return head;
}