Skip to content

Commit 1443c02

Browse files
committed
feat: add Reorder List
1 parent 19c7138 commit 1443c02

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ https://neetcode.io/roadmap
3939
| 567 | [Permutation in String](https://leetcode.com/problems/permutation-in-string/) | Medium | [ts](./TypeScript/567.permutation-in-string.ts) | Sliding Window |
4040
| 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | Easy | [ts](./TypeScript/206.reverse-linked-list.ts) [rkt](./Racket/206.reverse-linked-list.rkt) | Linked List |
4141
| 21 | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | Easy | [ts](./TypeScript/21.merge-two-sorted-lists.ts) [rkt](./Racket/21.merge-two-sorted-lists.rkt) | Linked List |
42+
| 143 | [Reorder List](https://leetcode.com/problems/reorder-list/) | Medium | [ts](./TypeScript/143.reorder-list.ts) | Linked List |
4243

4344
### Others
4445

TypeScript/143.reorder-list.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
interface ListNode {
2+
val: number;
3+
next: ListNode | null;
4+
}
5+
6+
function reorderList(head: ListNode | null): void {
7+
let slow: ListNode | null | undefined = head;
8+
let fast: ListNode | null | undefined = head?.next;
9+
let midpoint: ListNode | null | undefined = null;
10+
11+
// get midpoint
12+
while (fast && fast.next) {
13+
slow = slow?.next;
14+
fast = fast.next.next;
15+
}
16+
if (!slow?.next) return;
17+
midpoint = slow.next;
18+
slow.next = null;
19+
20+
// reverse
21+
let reversed: ListNode | null = null;
22+
while (midpoint) {
23+
let next = midpoint.next;
24+
25+
midpoint.next = reversed;
26+
reversed = midpoint;
27+
midpoint = next;
28+
}
29+
30+
// merge
31+
let n1 = head;
32+
let n2 = reversed;
33+
while (n1 && n2) {
34+
let next1 = n1.next;
35+
let next2 = n2.next;
36+
37+
n1.next = n2;
38+
n2.next = next1;
39+
40+
n1 = next1;
41+
n2 = next2;
42+
}
43+
}

0 commit comments

Comments
 (0)