-
Notifications
You must be signed in to change notification settings - Fork 4
/
Add 1 to Linked List.js
70 lines (54 loc) · 1.25 KB
/
Add 1 to Linked List.js
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
//A number is given represented in the form of a linked list. Add one to it.
const LinkedListNode = class {
constructor(nodeData) {
this.data = nodeData;
this.next = null;
}
};
var addOneToLinkedList = function(head) {
var node=new LinkedListNode(0);
node.next=head;
//reverse
var previous = null;
var current = node;
var next = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
node = previous;
var cur=node;
var carry;
while(cur!=null){
if(cur.data+1>9){
carry=1;
if(carry==1){
cur.data=0;
cur=cur.next;
carry=0;
}
}
else{
cur.data=cur.data+1;
break;
}
}
var previous = null;
var current = node;
var next = null;
while (current != null) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
node = previous;
if(node.data==0){
return node.next;
}
else{
return node;
}
};