Skip to content

Commit 42fc76d

Browse files
committed
feat: Upload reorder-list (typescript)
1 parent 4b3bce3 commit 42fc76d

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

โ€Žreorder-list/mike2ox.ts

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* Source: https://leetcode.com/problems/reorder-list/
3+
* ํ’€์ด๋ฐฉ๋ฒ•: ์ž„์‹œ ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•ด์„œ ํˆฌํฌ์ธํŠธ ์ „๋žต์œผ๋กœ ํ’‚
4+
* ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
5+
* ๊ณต๊ฐ„๋ณต์žก๋„: O(n)
6+
*
7+
* ์ถ”๊ฐ€ ํ’€์ด
8+
* - node๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ๋‘ ์ธ์ž๋งŒ ์‚ฌ์šฉํ•ด์„œ ํˆฌํฌ์ธํŠธ ์ „๋žต์ด ๊ฐ€๋Šฅ(but, ๊ตฌํ˜„ x)
9+
/
10+
11+
/**
12+
* Definition for singly-linked list.
13+
* class ListNode {
14+
* val: number
15+
* next: ListNode | null
16+
* constructor(val?: number, next?: ListNode | null) {
17+
* this.val = (val===undefined ? 0 : val)
18+
* this.next = (next===undefined ? null : next)
19+
* }
20+
* }
21+
*/
22+
23+
/**
24+
Do not return anything, modify head in-place instead.
25+
*/
26+
function reorderList(head: ListNode | null): void {
27+
if (!head || !head.next) return;
28+
29+
// 1. ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๋ฐฐ์—ด์— ์ €์žฅ
30+
const nodes: ListNode[] = [];
31+
let current: ListNode | null = head;
32+
while (current) {
33+
nodes.push(current);
34+
current = current.next;
35+
}
36+
37+
// 2. ๋ฐฐ์—ด์˜ ์–‘๋์—์„œ ์‹œ์ž‘ํ•˜์—ฌ ๋ฆฌ์ŠคํŠธ ์žฌ๊ตฌ์„ฑ
38+
let left = 0;
39+
let right = nodes.length - 1;
40+
41+
while (left < right) {
42+
// ํ˜„์žฌ ์™ผ์ชฝ ๋…ธ๋“œ์˜ ๋‹ค์Œ์„ ์ €์žฅ
43+
nodes[left].next = nodes[right];
44+
left++;
45+
46+
if (left === right) break;
47+
48+
// ํ˜„์žฌ ์˜ค๋ฅธ์ชฝ ๋…ธ๋“œ๋ฅผ ๋‹ค์Œ ์™ผ์ชฝ ๋…ธ๋“œ์— ์—ฐ๊ฒฐ
49+
nodes[right].next = nodes[left];
50+
right--;
51+
}
52+
53+
// ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ์˜ next๋ฅผ null๋กœ ์„ค์ •
54+
nodes[left].next = null;
55+
}

0 commit comments

Comments
ย (0)