-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0143-reorder-list.js
More file actions
54 lines (43 loc) · 1.1 KB
/
0143-reorder-list.js
File metadata and controls
54 lines (43 loc) · 1.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
43
44
45
46
47
48
49
50
51
52
53
54
/**
* https://leetcode.com/problems/reorder-list/
* Time O(N) | Space O(1)
* @param {ListNode} head
* @return {void} Do not return anything, modify head in-place instead.
*/
var reorderList = function (head) {
const mid = getMid(head); /* Time O(N) */
const reversedFromMid = reverse(mid); /* Time O(N) */
reorder(head, reversedFromMid); /* Time O(N) */
};
const getMid = (head) => {
let [slow, fast] = [head, head];
while (fast && fast.next) {
/* Time O(N) */
slow = slow.next;
fast = fast.next.next;
}
return slow;
};
const reverse = (head) => {
let [prev, curr, next] = [null, head, null];
while (curr) {
/* Time O(N) */
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
};
const reorder = (l1, l2) => {
let [first, next, second] = [l1, null, l2];
while (second.next) {
/* Time O(N) */
next = first.next;
first.next = second;
first = next;
next = second.next;
second.next = first;
second = next;
}
};