-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd_1_to_number_represented_by_list.cpp
77 lines (61 loc) · 1.08 KB
/
Add_1_to_number_represented_by_list.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>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
struct Node* head = NULL;
void insert(int key)
{
Node* newNode = new Node;
newNode->data = key;
newNode->next = head;
head = newNode;
}
void display()
{
Node* ptr;
ptr = head;
while(ptr != NULL)
{
cout<< ptr->data <<" ";
ptr = ptr->next;
}
}
Node* addOne()
{
Node *temp = head;
string s;
int i = 0;
while(temp->next != NULL)
{
int a = temp->data;
s.insert(i++ , to_string(a));
temp = temp->next;
}
int a = temp->data;
s.insert(i++ , to_string(a));
stringstream geek(s);
int x = 0;
geek >> x;
temp->data = x+1;
temp->next = NULL;
free(head);
head = temp;
}
int main()
{
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The linked list is: ";
display();
addOne();
cout<<"\nThe updated linked list after adding 1 to a number represented as linked list : ";
display();
cout<<endl;
return 0;
}