-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_a_linked_list.js
More file actions
42 lines (35 loc) · 1 KB
/
Copy pathreverse_a_linked_list.js
File metadata and controls
42 lines (35 loc) · 1 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
class Node {
constructor(value, next=null){
this.value = value;
this.next = next;
}
get_list() {
let result = "";
let temp = this;
while (temp !== null) {
result += temp.value + " ";
temp = temp.next;
}
return result;
}
};
const reverse = function(head) {
//in any iteration. point current to previous.
//reset the current head.
let previous = null;
let current = head;
while (current != null) {
let next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
};
head = new Node(2);
head.next = new Node(4);
head.next.next = new Node(6);
head.next.next.next = new Node(8);
head.next.next.next.next = new Node(10);
console.log(`Nodes of original LinkedList are: ${head.get_list()}`)
console.log(`Nodes of reversed LinkedList are: ${reverse(head).get_list()}`)