Skip to content

Commit 9b54edd

Browse files
committed
feat(soobing): week11 > reorder-list
1 parent 53f7ba6 commit 9b54edd

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

reorder-list/soobing.ts

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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+
Do not return anything, modify head in-place instead.
12+
*/
13+
14+
function reverseList(head: ListNode | null) {
15+
let prev: ListNode | null = null;
16+
let cur: ListNode | null = head;
17+
18+
while (cur) {
19+
const next = cur.next;
20+
cur.next = prev;
21+
prev = cur;
22+
cur = next;
23+
}
24+
25+
return prev;
26+
}
27+
28+
function reorderList(head: ListNode | null): void {
29+
if (!head || !head.next) return;
30+
31+
// 1. 중간 지점 찾기
32+
let slow: ListNode | null = head;
33+
let fast: ListNode | null = head;
34+
35+
while (fast && fast.next) {
36+
slow = slow!.next;
37+
fast = fast.next.next;
38+
}
39+
40+
// 2. 리스트 절단
41+
const secondHead = slow!.next;
42+
slow!.next = null;
43+
44+
// 3. 뒤쪽 리스트 뒤집기
45+
let second: ListNode | null = reverseList(secondHead);
46+
47+
// 4. 병합
48+
let first: ListNode | null = head;
49+
50+
while (second) {
51+
let tmp1 = first!.next;
52+
let tmp2 = second.next;
53+
54+
first!.next = second;
55+
second.next = tmp1;
56+
57+
first = tmp1;
58+
second = tmp2;
59+
}
60+
}

0 commit comments

Comments
 (0)