Skip to content

Commit d3ee6ec

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

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

143-reorder-list.js

+45
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,48 @@
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 == null) return head
14+
let slow = head, fast = head
15+
while(fast && fast.next) {
16+
slow = slow.next
17+
fast = fast.next.next
18+
}
19+
let head2 = reverse(slow.next)
20+
slow.next = null
21+
22+
while(head && head2) {
23+
const next = head.next, next2 = head2.next
24+
head2.next = head.next
25+
head.next = head2
26+
head = next
27+
head2 = next2
28+
}
29+
30+
function reverse(node) {
31+
let pre = null, cur = node
32+
while(cur) {
33+
const tmp = cur.next
34+
cur.next = pre
35+
pre = cur
36+
cur = tmp
37+
}
38+
return pre
39+
}
40+
};
41+
42+
43+
44+
// another
45+
146
/**
247
* Definition for singly-linked list.
348
* function ListNode(val) {

0 commit comments

Comments
 (0)