-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked-list-reverse.js
57 lines (48 loc) · 1.04 KB
/
linked-list-reverse.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
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
// class LinkedList {
// constructor() {
// this.head = null;
// }
// }
const a = new Node("a");
const b = new Node("b");
const c = new Node("c");
const d = new Node("d");
a.next = b;
b.next = c;
c.next = d;
const print = (head) => {
if (head === null) return;
console.log(head.val + "=> ");
print(head.next);
};
const reverseList = (head) => {
let prev = null;
let curr = head;
while (curr !== null) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
};
const reverseListRec = (curr, prev = null) => {
if (curr === null) {
return prev;
}
const next = curr.next;
curr.next = prev;
return reverseListRec(next, curr);
};
print(a);
// a, b, c, d
// const newHead = reverseList(a);
const newHead = reverseListRec(a);
console.log("reversing...");
print(newHead);