-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_one_to_a_linked_list.cpp
More file actions
78 lines (68 loc) · 1.44 KB
/
Copy pathadd_one_to_a_linked_list.cpp
File metadata and controls
78 lines (68 loc) · 1.44 KB
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
/**
* Definition of linked list:
*
* class Node {
* public:
* int data;
* Node *next;
* Node() {
* this->data = 0;
* this->next = NULL;
* }
* Node(int data) {
* this->data = data;
* this->next = NULL;
* }
* Node (int data, Node *next) {
* this->data = data;
* this->next = next;
* }
* };
*
*************************************************************************/
Node *reverseLL(Node *head){
Node *node = NULL;
while(head){
Node *temp = head->next;
head->next = node;
node = head;
head = temp;
}
return node;
}
Node *addOne(Node *head)
{
Node *newHead = reverseLL(head);
Node *t = newHead;
int carry = 1;
Node *prev = t;
while(t && carry){
int sum = carry + t->data;
t->data = sum % 10;
carry = sum / 10;
prev = t;
t = t->next;
}
if(carry)
prev->next = new Node(carry);
return reverseLL(newHead);
}
// another approach using recursion
int addHelper(Node *temp){
if(temp == NULL) return 1;
int carry = addHelper(temp->next);
temp->data += carry;
if(temp->data < 10) return 0;
temp->data = 0;
return 1;
}
Node *addOne(Node *head)
{
int carry = addHelper(head);
if(carry == 1){
Node *nnode = new Node(1);
nnode->next = head;
head = nnode;
}
return head;
}