Skip to content

Commit 51181ff

Browse files
committed
Add reorder-list solution
1 parent a7e9cad commit 51181ff

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

reorder-list/Jeehay28.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// ✅ Time Complexity: O(N)
2+
// ✅ Space Complexity: O(N) (due to the stack storage)
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+
/**
13+
* @param {ListNode} head
14+
* @return {void} Do not return anything, modify head in-place instead.
15+
*/
16+
var reorderList = function (head) {
17+
let stack = [];
18+
let node = head;
19+
20+
while (node) {
21+
stack.push(node);
22+
node = node.next;
23+
}
24+
25+
let dummy = new ListNode(-1);
26+
node = dummy;
27+
28+
const len = stack.length;
29+
30+
for (let i = 0; i < len; i++) {
31+
if (i % 2 === 1) {
32+
node.next = stack.pop();
33+
} else {
34+
node.next = head;
35+
head = head.next;
36+
}
37+
node = node.next;
38+
}
39+
40+
node.next = null;
41+
return dummy.next;
42+
};
43+

0 commit comments

Comments
 (0)