Skip to content

Commit eaf5d55

Browse files
committed
reorder list solution
1 parent 931bcdf commit eaf5d55

1 file changed

Lines changed: 81 additions & 0 deletions

File tree

โ€Žreorder-list/smosco.jsโ€Ž

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
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+
/**
10+
* ๋ฐฉ๋ฒ• 1: ๋ฐ˜์œผ๋กœ ๋‚˜๋ˆ„๊ธฐ + ๋’ค์ง‘๊ธฐ + ํ•ฉ์น˜๊ธฐ
11+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
12+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
13+
* @param {ListNode} head
14+
* @return {void} Do not return anything, modify head in-place instead.
15+
*/
16+
var reorderList = function (head) {
17+
if (!head || !head.next) return;
18+
19+
// 1. ์ค‘๊ฐ„ ์ง€์  ์ฐพ๊ธฐ (slow-fast pointer)
20+
let slow = head,
21+
fast = head;
22+
while (fast.next && fast.next.next) {
23+
slow = slow.next;
24+
fast = fast.next.next;
25+
}
26+
27+
// 2. ๋’ท๋ถ€๋ถ„ ๋ฆฌ์ŠคํŠธ ๋ถ„๋ฆฌ ๋ฐ ๋’ค์ง‘๊ธฐ
28+
let second = slow.next;
29+
slow.next = null;
30+
31+
let prev = null;
32+
while (second) {
33+
let temp = second.next;
34+
second.next = prev;
35+
prev = second;
36+
second = temp;
37+
}
38+
39+
// 3. ๋‘ ๋ฆฌ์ŠคํŠธ ํ•ฉ์น˜๊ธฐ
40+
let first = head;
41+
second = prev;
42+
while (second) {
43+
let temp1 = first.next;
44+
let temp2 = second.next;
45+
first.next = second;
46+
second.next = temp1;
47+
first = temp1;
48+
second = temp2;
49+
}
50+
};
51+
52+
/**
53+
* ๋ฐฉ๋ฒ• 2: Stack ์‚ฌ์šฉ
54+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
55+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n)
56+
* @param {ListNode} head
57+
* @return {void} Do not return anything, modify head in-place instead.
58+
*/
59+
var reorderListStack = function (head) {
60+
if (!head || !head.next) return;
61+
62+
// ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ์Šคํƒ์— ์ €์žฅ
63+
let stack = [];
64+
let curr = head;
65+
while (curr) {
66+
stack.push(curr);
67+
curr = curr.next;
68+
}
69+
70+
// ์•ž์—์„œ๋ถ€ํ„ฐ, ๋’ค์—์„œ๋ถ€ํ„ฐ ๋ฒˆ๊ฐˆ์•„ ์—ฐ๊ฒฐ
71+
let len = stack.length;
72+
curr = head;
73+
for (let i = 0; i < Math.floor(len / 2); i++) {
74+
let last = stack.pop();
75+
let temp = curr.next;
76+
curr.next = last;
77+
last.next = temp;
78+
curr = temp;
79+
}
80+
curr.next = null; // ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ ์ฒ˜๋ฆฌ
81+
};

0 commit comments

Comments
ย (0)