forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0143-reorder-list.js
51 lines (40 loc) · 1.13 KB
/
0143-reorder-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
/**
* 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 reveredFromMid = reverse(mid);/* Time O(N) */
reorder(head, reveredFromMid); /* 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;
}
}