-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-023-reverseList.js
63 lines (51 loc) · 1.25 KB
/
structy-023-reverseList.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
// https://structy.net/problems/reverse-list
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
// p: head of ll
// r: new head
// null a ----------> b ----------> c
// head
// <-c.n-----cur
// tail
// recursion
const reverseList = (head, tail = null) => {
if (!head) return tail;
let current = head;
head = current.next;
current.next = tail;
tail = current;
// console.log(head, tail);
return reverseList(head, tail);
};
// null a ----------> b ----------> c
// t <--cur.n-- cur head
// // iteratioin
// const reverseList = (head) => {
// let current = head;
// let tail = null;
// while (current) {
// head = current.next;
// current.next = tail;
// tail = current;
// current = head;
// }
// // console.log(current);
// return tail;
// };
const a = new Node("a");
const b = new Node("b");
const c = new Node("c");
const d = new Node("d");
const e = new Node("e");
const f = new Node("f");
a.next = b;
b.next = c;
c.next = d;
d.next = e;
e.next = f;
// a -> b -> c -> d -> e -> f
console.log(reverseList(a)); // f -> e -> d -> c -> b -> a