|
| 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