Skip to content

Commit c94dacb

Browse files
authored
[ PS ] : Reorder List
1 parent 19f1310 commit c94dacb

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

โ€Žreorder-list/uraflower.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @return {void} Do not return anything, modify head in-place instead.
11+
*/
12+
var reorderList = function (head) {
13+
const nodes = {};
14+
let current = head;
15+
let n = 0; // ์ธ๋ฑ์Šค ์—ญํ• 
16+
17+
// ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ๊ฐ ๋…ธ๋“œ๋ฅผ ๊ฐ์ฒด์— ์ €์žฅ
18+
while (current) {
19+
nodes[n] = current;
20+
current = current.next;
21+
nodes[n].next = null; // ์—ฌ๊ธฐ์„œ ๋ชจ๋“  ๋…ธ๋“œ์˜ next๋ฅผ null๋กœ ๋ณ€๊ฒฝ
22+
// ์ด๋ ‡๊ฒŒ ์•ˆ ํ•˜๋ฉด next ๋ฐ”๊พธ๊ธฐ ํ•œ ๋‹ค์Œ์— ๋งจ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ์˜ next๋งŒ null๋กœ ๋ฐ”๊ฟ”์•ผ ํ•จ
23+
n++
24+
}
25+
26+
// ์ €์žฅํ•œ ๋…ธ๋“œ๋ฅผ i, n-i, ... ์ˆœ์„œ๋กœ ์ ‘๊ทผํ•˜๋ฉด์„œ next ๋ฐ”๊พธ๊ธฐ
27+
for (let i = 0; i < Math.floor(n / 2); i++) {
28+
nodes[i].next = nodes[n - i - 1];
29+
30+
// n-i-1 === i+1 ์ธ ๊ฒฝ์šฐ, node.next = node ์ฒ˜๋Ÿผ ์…€ํ”„ ์ˆœํ™˜์ด ๋  ์ˆ˜ ์žˆ์Œ
31+
if (n - i - 1 !== i + 1) {
32+
nodes[n - i - 1].next = nodes[i + 1];
33+
}
34+
}
35+
};
36+
37+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
38+
// ๊ณต๊ฐ„๋ณต์žก๋„: O(n)

0 commit comments

Comments
ย (0)