Skip to content

Commit 7fce08f

Browse files
committed
feat: 143. Reorder List
1 parent e4deb82 commit 7fce08f

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

reorder-list/gwbaik9717.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// Time complexity: O(n)
2+
// Space complexity: O(n)
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* function ListNode(val, next) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
*/
11+
/**
12+
* @param {ListNode} head
13+
* @return {void} Do not return anything, modify head in-place instead.
14+
*/
15+
var reorderList = function (head) {
16+
const nodes = [];
17+
let n = 0;
18+
19+
{
20+
let current = head;
21+
while (current) {
22+
n++;
23+
nodes.push(current);
24+
current = current.next;
25+
}
26+
}
27+
28+
const answer = head;
29+
30+
{
31+
let current = answer;
32+
for (let i = 1; i < n; i++) {
33+
if (i % 2 !== 0) {
34+
current.next = nodes.at(n - Math.ceil(i / 2));
35+
} else {
36+
current.next = nodes.at(i / 2);
37+
}
38+
39+
current = current.next;
40+
}
41+
42+
current.next = null;
43+
}
44+
45+
return answer;
46+
};

0 commit comments

Comments
 (0)