Skip to content

Commit c0da1e6

Browse files
committed
Add week 7 solutions : reorderList
1 parent e25d7e3 commit c0da1e6

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

reorder-list/yolophg.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(n)
3+
4+
var reorderList = function (head) {
5+
// push all nodes onto a stack.
6+
let stack = [];
7+
let current = head;
8+
while (current) {
9+
stack.push(current);
10+
current = current.next;
11+
}
12+
13+
// reorder the list.
14+
let n = stack.length;
15+
current = head;
16+
17+
for (let i = 0; i < Math.floor(n / 2); i++) {
18+
let next = current.next;
19+
let last = stack.pop();
20+
21+
current.next = last;
22+
last.next = next;
23+
current = next;
24+
}
25+
// ensure the last node points to null.
26+
if (current) current.next = null;
27+
};

0 commit comments

Comments
 (0)