forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHC-kang.ts
47 lines (40 loc) ยท 984 Bytes
/
HC-kang.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
/**
* https://leetcode.com/problems/reorder-list
* T.C. O(n)
* S.C. O(1)
*/
function reorderList(head: ListNode | null): void {
if (!head || !head.next) return;
let fast: ListNode | null = head;
let slow: ListNode | null = head;
while (fast && fast.next) {
fast = fast.next.next;
slow = slow!.next;
}
let prev: ListNode | null = null;
let curr: ListNode | null = slow;
while (curr) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
let front: ListNode | null = head;
let back: ListNode | null = prev;
while (back!.next) {
const frontNext = front!.next;
const backNext = back!.next;
front!.next = back;
back!.next = frontNext;
front = frontNext;
back = backNext;
}
}