-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add 1 to a Linked List Number.cpp
63 lines (53 loc) · 1.06 KB
/
Add 1 to a Linked List Number.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
// User function template for C++
/*
struct Node
{
int data;
struct Node* next;
Node(int x){
data = x;
next = NULL;
}
};
*/
// Time complexity - O(N)
// Space complexity- O(1) - constant
class Solution {
public:
Node* reverse(Node* head)
{
Node* pre=NULL;
Node* h=head;
while(h)
{
Node* nextNode=h->next;
h->next=pre;
pre=h;
h=nextNode;
}
return pre;
}
Node* addOne(Node* head) {
// reverse linked list
Node* reverseHead=reverse(head);
Node* h=reverseHead;
Node* pre=NULL;
int carry=1;
while(h)
{
int add=h->data+carry;
h->data=add%10;
carry=add/10;
pre=h;
h=h->next;
}
if(carry)
{
Node* newNode=new Node(carry);
pre->next=newNode;
carry=0;
}
Node* ansHead=reverse(reverseHead);
return ansHead;
}
};