-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathAdd 1 to number represented by the linked list.cpp
88 lines (77 loc) · 1.67 KB
/
Add 1 to number represented by the linked 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
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node* next;
};
Node *newNode(int data)
{
Node *new_node = new Node;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
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;
}
Node *addOneUtil(Node *head)
{ Node* res = head;
Node *temp, *prev = NULL;
int carry = 1, sum;
while (head != NULL) //while both lists exist
{ sum = carry + head->data;
carry = (sum >= 10)? 1 : 0;
sum = sum % 10;
head->data = sum;
temp = head;
head = head->next;
}
Node* addOne(Node *head)
{
head = reverse(head);
head = addOneUtil(head);
return reverse(head);
}
void printList(Node *node)
{
while (node != NULL)
{
cout << node->data;
node = node->next;
}
cout<<endl;
}
int main(void)
{
Node *head = newNode(1);
head->next = newNode(9);
head->next->next = newNode(9);
head->next->next->next = newNode(9);
cout << "List is ";
printList(head);
head = addOne(head);
cout << "\nResultant list is ";
printList(head);
return 0;
}
//Input Format:
//Enter the value of the nodes of the linked list.
//Output Format:
//Add 1 to the number represented by the linked list.
//Sample Input Format:
//1->9->9->->9
//Sample Output Format:
//2000