-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01-reverse_list.js
More file actions
48 lines (42 loc) · 866 Bytes
/
01-reverse_list.js
File metadata and controls
48 lines (42 loc) · 866 Bytes
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
function createNode(value) {
return {
value: value,
next: null,
};
}
function add (lst, value){
var new_node = createNode(value);
new_node.next = lst.head;
lst.head = new_node;
return lst.head;
}
function printList(lst){
var cur = lst.head;
while(cur != null){
console.log(cur.value);
cur = cur.next;
}
}
function reverseList(lst, cur){
if(cur.next == null){
lst.head = cur;
return cur;
}
prev = reverseList(lst, cur.next);
prev.next = cur;
cur.next = null;
return cur;
}
// Create a new Linked List
// head = 2 -> 6 -> 5 -> 1 -> Null
var linkedList = {
head : null,
};
add(linkedList, 1);
add(linkedList, 3);
add(linkedList, 4);
add(linkedList, 6);
add(linkedList, 8);
printList(linkedList);
reverseList(linkedList, linkedList.head)
printList(linkedList);