Skip to content

Commit 7895f3a

Browse files
authored
Update 143-reorder-list.js
1 parent 75b4bc7 commit 7895f3a

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

143-reorder-list.js

+54
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,57 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val) {
4+
* this.val = val;
5+
* this.next = null;
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @return {void} Do not return anything, modify head in-place instead.
11+
*/
12+
const reorderList = function(head) {
13+
if (!head || !head.next) return head;
14+
15+
const reverse = head => {
16+
if (!head || !head.next) return head;
17+
const newHead = reverse(head.next);
18+
head.next.next = head;
19+
head.next = null;
20+
return newHead;
21+
};
22+
23+
const merge = (l1, l2) => {
24+
if (!l1) return l2;
25+
if (!l2) return l1;
26+
while (l1 && l2) {
27+
const next1 = l1.next;
28+
const next2 = l2.next;
29+
l1.next = l2;
30+
if (next1 == null) break;
31+
l2.next = next1;
32+
l1 = next1;
33+
l2 = next2;
34+
}
35+
};
36+
37+
let fast = head;
38+
let slow = head;
39+
40+
while (fast && fast.next) {
41+
fast = fast.next.next;
42+
slow = slow.next;
43+
}
44+
45+
fast = slow.next;
46+
slow.next = null;
47+
48+
fast = reverse(fast);
49+
merge(head, fast);
50+
};
51+
52+
53+
// another
54+
155
/**
256
* Definition for singly-linked list.
357
* function ListNode(val) {

0 commit comments

Comments
 (0)