Skip to content

Commit 353b541

Browse files
committed
Add week 11 solutions: reorder-list
1 parent b0dbcb2 commit 353b541

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

reorder-list/gitsunmin.ts

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* https://leetcode.com/problems/reorder-list/
3+
* time complexity : O(n)
4+
* space complexity : O(1)
5+
*/
6+
7+
class ListNode {
8+
val: number
9+
next: ListNode | null
10+
constructor(val?: number, next?: ListNode | null) {
11+
this.val = (val === undefined ? 0 : val)
12+
this.next = (next === undefined ? null : next)
13+
}
14+
}
15+
16+
function reorderList(head: ListNode | null): void {
17+
if (!head || !head.next) return;
18+
19+
// 1. 중간 지점 찾기 (Floyd’s Tortoise and Hare)
20+
let slow: ListNode | null = head;
21+
let fast: ListNode | null = head;
22+
23+
while (fast && fast.next) {
24+
slow = slow!.next;
25+
fast = fast.next.next;
26+
}
27+
28+
// 2. 중간 이후의 리스트 뒤집기
29+
let prev: ListNode | null = null;
30+
let curr: ListNode | null = slow;
31+
32+
while (curr) {
33+
const next = curr.next;
34+
curr.next = prev;
35+
prev = curr;
36+
curr = next;
37+
}
38+
39+
// 3. 앞부분과 뒤집어진 후반부 병합
40+
let first: ListNode | null = head;
41+
let second: ListNode | null = prev;
42+
43+
while (second && second.next) {
44+
const temp1 = first!.next;
45+
const temp2 = second.next;
46+
47+
first!.next = second;
48+
second.next = temp1;
49+
50+
first = temp1;
51+
second = temp2;
52+
}
53+
};

0 commit comments

Comments
 (0)