Skip to content

Commit 9552cd9

Browse files
Jeehay28Jeehay28
authored andcommitted
Add reorder-list solution in TS
1 parent 9879785 commit 9552cd9

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

reorder-list/Jeehay28.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class ListNode {
2+
val: number;
3+
next: ListNode | null;
4+
constructor(val?: number, next?: ListNode | null) {
5+
this.val = val === undefined ? 0 : val;
6+
this.next = next === undefined ? null : next;
7+
}
8+
}
9+
10+
/**
11+
Do not return anything, modify head in-place instead.
12+
*/
13+
14+
// TC: O(n)
15+
// SC: O(n)
16+
function reorderList(head: ListNode | null): void {
17+
const nodes: ListNode[] = [];
18+
19+
while (head) {
20+
nodes.push(head);
21+
head = head.next;
22+
}
23+
24+
let start = 0;
25+
let end = nodes.length - 1;
26+
27+
while (start < end) {
28+
nodes[start].next = nodes[end];
29+
start++;
30+
if (start === end) break;
31+
nodes[end].next = nodes[start];
32+
end--;
33+
}
34+
35+
nodes[start].next = null;
36+
}

0 commit comments

Comments
 (0)