-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path206_reverse_linked_list.js
59 lines (51 loc) · 1011 Bytes
/
206_reverse_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
// tags: #linkedlist #hot
// https://leetcode.cn/problems/reverse-linked-list/
// version 1
// time: 68ms
var reverseList = function (head) {
if (!head) return null;
let root;
traverse(null, head);
return root;
function traverse(pre, cur) {
if (!cur) {
root = pre;
return;
}
traverse(cur, cur.next);
cur.next = pre;
}
};
// version 2
// time: 64ms | beat: 66%
var reverseList = function (head) {
if (!head) return null;
let pre = null;
let cur = head;
let next = head.next;
while (cur) {
cur.next = pre;
pre = cur;
cur = next;
next = next?.next;
}
return pre;
};
/* test code */
class ListNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
function generateList(arr) {
let root = new ListNode(arr[0]);
let cur = root;
for (let i = 1; i < arr.length; i++) {
cur.next = new ListNode(arr[i]);
cur = cur.next;
}
return root;
}
const list = reverseList(generateList([1, 2, 3, 4, 5]));
debugger;