Skip to content

Commit bc2b7d1

Browse files
committed
feat: reorder-list solution
1 parent c472fbc commit bc2b7d1

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
/**
14+
Do not return anything, modify head in-place instead.
15+
*/
16+
17+
/**
18+
* ๋ฆฌ์ŠคํŠธ ์žฌ์ •๋ ฌ ํ•˜๊ธฐ (0 -> n -> 1 -> n-1 -> ...)
19+
* ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ณต์žก๋„
20+
* - ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
21+
* - ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n)
22+
* @param head
23+
*/
24+
function reorderList(head: ListNode | null): void {
25+
if (!head || !head.next) return;
26+
27+
const stack: ListNode[] = [];
28+
let node = head;
29+
while (node) {
30+
stack.push(node);
31+
node = node.next;
32+
}
33+
34+
let left = 0;
35+
let right = stack.length - 1;
36+
37+
while (left < right) {
38+
// ํ˜„์žฌ ๋…ธ๋“œ์˜ ๋‹ค์Œ์— ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ ์—ฐ๊ฒฐ
39+
stack[left].next = stack[right];
40+
left++;
41+
42+
// ๋‚จ์€ ๋…ธ๋“œ๊ฐ€ ์žˆ์œผ๋ฉด ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ์˜ ๋‹ค์Œ์— ๋‹ค์Œ ์™ผ์ชฝ ๋…ธ๋“œ ์—ฐ๊ฒฐ
43+
if (left < right) {
44+
stack[right].next = stack[left];
45+
right--;
46+
}
47+
}
48+
49+
// ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ์˜ next๋ฅผ null๋กœ ์„ค์ •
50+
stack[left].next = null;
51+
}

0 commit comments

Comments
ย (0)