-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_1.cpp
108 lines (86 loc) · 1.32 KB
/
add_1.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
//add 1 to a number represented by linked list
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
node(int x)
{
data = x;
next = NULL;
}
};
node *buildLinkedlist(int n)
{
int x;
cout << "Enter space separated digits: ";
cin >> x;
node *head = new node(x);
node *tail = head;
for(int i = 0; i < n-1; i++)
{
cin >> x;
tail->next = new node(x);
tail = tail->next;
}
return head;
}
node *reverse(node *head)
{
node *prev = NULL;
node *current = head;
node *next;
while(current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
void display(node *p)
{
while(p != NULL)
{
cout << p->data;
p = p->next;
}
cout << "\n";
}
node *add_1_to(node *head)
{
head = reverse(head);
int carry = 1, sum = 0;
node *res = head;
node *temp, *prev = NULL;
while(head != NULL)
{
sum = carry + head->data;
carry = (sum >= 10) ? 1:0;
sum = sum%10;
head->data = sum;
temp = head;
head = head->next;
}
if(carry)
{
temp->next = new node(carry);
}
res = reverse(res);
return res;
}
int main()
{
int n, m;
cout << "Enter no. of digits: ";
cin >> n;
node *num = buildLinkedlist(n);
cout << "Number is: ";
display(num);
node *ans = add_1_to(num);
cout << "Answer :";
display(ans);
return 0;
}