forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYeomChaeeun.ts
51 lines (44 loc) ยท 1.14 KB
/
YeomChaeeun.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
/**
* 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.
*/
/**
* ๋ฆฌ์คํธ ์ฌ์ ๋ ฌ ํ๊ธฐ (0 -> n -> 1 -> n-1 -> ...)
* ์๊ณ ๋ฆฌ์ฆ ๋ณต์ก๋
* - ์๊ฐ ๋ณต์ก๋: O(n)
* - ๊ณต๊ฐ ๋ณต์ก๋: O(n)
* @param head
*/
function reorderList(head: ListNode | null): void {
if (!head || !head.next) return;
const stack: ListNode[] = [];
let node = head;
while (node) {
stack.push(node);
node = node.next;
}
let left = 0;
let right = stack.length - 1;
while (left < right) {
// ํ์ฌ ๋
ธ๋์ ๋ค์์ ๋ง์ง๋ง ๋
ธ๋ ์ฐ๊ฒฐ
stack[left].next = stack[right];
left++;
// ๋จ์ ๋
ธ๋๊ฐ ์์ผ๋ฉด ๋ง์ง๋ง ๋
ธ๋์ ๋ค์์ ๋ค์ ์ผ์ชฝ ๋
ธ๋ ์ฐ๊ฒฐ
if (left < right) {
stack[right].next = stack[left];
right--;
}
}
// ๋ง์ง๋ง ๋
ธ๋์ next๋ฅผ null๋ก ์ค์
stack[left].next = null;
}