-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
49 lines (42 loc) · 1.09 KB
/
solution.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
// Reorder List
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
class ListNode {
constructor(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.
*/
const reorderList = (head) => {
if (null === head.next) return head;
let slow = head, fast = head.next.next, reversed = new ListNode(), dummy = new ListNode(), result = dummy;
while (fast) {
reversed.next = new ListNode(fast.val, reversed.next);
fast = fast.next;
}
reversed = reversed.next;
while (slow && reversed) {
if (slow.val === reversed.val) {
dummy.next = reversed;
slow = null;
reversed = null;
} else {
dummy.next = slow;
slow = slow.next;
dummy = dummy.next;
dummy.next = reversed;
reversed = reversed.next;
dummy = dummy.next;
}
}
head = result.next;
};