forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmike2ox.ts
55 lines (47 loc) ยท 1.38 KB
/
mike2ox.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* Source: https://leetcode.com/problems/reorder-list/
* ํ์ด๋ฐฉ๋ฒ: ์์ ๋ฐฐ์ด์ ์ฌ์ฉํด์ ํฌํฌ์ธํธ ์ ๋ต์ผ๋ก ํ
* ์๊ฐ๋ณต์ก๋: O(n)
* ๊ณต๊ฐ๋ณต์ก๋: O(n)
*
* ์ถ๊ฐ ํ์ด
* - node๋ฅผ ๊ฐ๋ฆฌํค๋ ๋ ์ธ์๋ง ์ฌ์ฉํด์ ํฌํฌ์ธํธ ์ ๋ต์ด ๊ฐ๋ฅ(but, ๊ตฌํ x)
/
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
/**
Do not return anything, modify head in-place instead.
*/
function reorderList(head: ListNode | null): void {
if (!head || !head.next) return;
// 1. ๋ชจ๋ ๋
ธ๋๋ฅผ ๋ฐฐ์ด์ ์ ์ฅ
const nodes: ListNode[] = [];
let current: ListNode | null = head;
while (current) {
nodes.push(current);
current = current.next;
}
// 2. ๋ฐฐ์ด์ ์๋์์ ์์ํ์ฌ ๋ฆฌ์คํธ ์ฌ๊ตฌ์ฑ
let left = 0;
let right = nodes.length - 1;
while (left < right) {
// ํ์ฌ ์ผ์ชฝ ๋
ธ๋์ ๋ค์์ ์ ์ฅ
nodes[left].next = nodes[right];
left++;
if (left === right) break;
// ํ์ฌ ์ค๋ฅธ์ชฝ ๋
ธ๋๋ฅผ ๋ค์ ์ผ์ชฝ ๋
ธ๋์ ์ฐ๊ฒฐ
nodes[right].next = nodes[left];
right--;
}
// ๋ง์ง๋ง ๋
ธ๋์ next๋ฅผ null๋ก ์ค์
nodes[left].next = null;
}