Skip to content

Commit 7e77421

Browse files
committed
Feat: 143. Reorder List
1 parent 0b08e22 commit 7e77421

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

reorder-list/HC-kang.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
* https://leetcode.com/problems/reorder-list
12+
* T.C. O(n)
13+
* S.C. O(1)
14+
*/
15+
function reorderList(head: ListNode | null): void {
16+
if (!head || !head.next) return;
17+
18+
let fast: ListNode | null = head;
19+
let slow: ListNode | null = head;
20+
21+
while (fast && fast.next) {
22+
fast = fast.next.next;
23+
slow = slow!.next;
24+
}
25+
26+
let prev: ListNode | null = null;
27+
let curr: ListNode | null = slow;
28+
while (curr) {
29+
const next = curr.next;
30+
curr.next = prev;
31+
prev = curr;
32+
curr = next;
33+
}
34+
35+
let front: ListNode | null = head;
36+
let back: ListNode | null = prev;
37+
while (back!.next) {
38+
const frontNext = front!.next;
39+
const backNext = back!.next;
40+
41+
front!.next = back;
42+
back!.next = frontNext;
43+
44+
front = frontNext;
45+
back = backNext;
46+
}
47+
}

0 commit comments

Comments
 (0)