Skip to content

Commit 48385f4

Browse files
committed
reorder list solution
1 parent d4daa7b commit 48385f4

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

reorder-list/hyer0705.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* val: number
5+
* next: ListNode | null
6+
* constructor(val?: number, next?: ListNode | null) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
* }
11+
*/
12+
13+
// Time Complexity: O(n)
14+
// Space Complexity: O(1)
15+
/**
16+
Do not return anything, modify head in-place instead.
17+
*/
18+
function reorderList(head: ListNode | null): void {
19+
if (!head || !head.next || !head.next.next) return;
20+
21+
let slow: ListNode | null = head;
22+
let fast: ListNode | null = head;
23+
24+
// find central node
25+
while (fast && fast.next) {
26+
slow = slow.next;
27+
fast = fast.next.next;
28+
}
29+
30+
let secondHalf = slow.next;
31+
slow.next = null;
32+
33+
// reverse secondHalf
34+
let prev = null;
35+
let curr = secondHalf;
36+
while (curr) {
37+
const nextTemp = curr.next;
38+
curr.next = prev;
39+
prev = curr;
40+
curr = nextTemp;
41+
}
42+
43+
let first = head;
44+
let second = prev;
45+
46+
while (second) {
47+
const firstNext = first.next;
48+
const secondNext = second.next;
49+
50+
first.next = second;
51+
second.next = firstNext;
52+
53+
first = firstNext;
54+
second = secondNext;
55+
}
56+
}

0 commit comments

Comments
 (0)