-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAdd_1_to_LL.cpp
60 lines (49 loc) · 1.11 KB
/
Add_1_to_LL.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
//User function template for C++
/*
struct Node
{
int data;
struct Node* next;
Node(int x){
data = x;
next = NULL;
}
};
*/
class Solution
{
public:
Node * reverse(Node * head)
{
Node * curr = head, *prev =NULL, *front = NULL;
while(curr){
front = curr->next;
curr->next = prev;
prev= curr;
curr = front;
}
return prev;
}
Node* addOne(Node *head)
{
// Your Code here
// return head of list after adding one
Node * rev = reverse(head);
Node * temp = rev , *tail;
while(temp){
if(temp->data == 9){
temp->data =0;
}
else{
temp->data = temp->data+1;
head = reverse(rev);
return head;
}
tail = temp;
temp=temp->next;
}
tail->next = new Node(1);
head= reverse(rev);
return head;
}
};