-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathreorder-list.js
64 lines (50 loc) · 1.4 KB
/
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
52
53
54
55
56
57
58
59
60
61
62
63
64
/**You are given the head of a singly linked-list. The list can be represented as:
L0 → L1 → … → Ln - 1 → Ln
Reorder the list to be on the following form:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
You may not modify the values in the list's nodes. Only nodes themselves may be changed. */
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {void} Do not return anything, modify head in-place instead.
*/
var reorderList = function(head) {
if (head === null) return null;
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
let firstHead = head;
let secondHead = reverseList(slow);
while (secondHead) {
let temp1 = firstHead.next;
let temp2 = secondHead.next;
firstHead.next = secondHead;
secondHead.next = temp1;
firstHead = temp1;
secondHead = temp2;
}
if (firstHead) {
firstHead.next = null;
}
return head;
};
function reverseList(node) {
let prev = null;
let curr = node;
while (curr) {
let next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}