Skip to content

Commit df3a36e

Browse files
reorder tree
1 parent 552e643 commit df3a36e

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

โ€Žreorder-list/jaejeong1.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import java.util.Stack;
2+
3+
// Definition for singly-linked list.
4+
class ListNode {
5+
6+
int val;
7+
ListNode next;
8+
9+
ListNode() {
10+
}
11+
12+
ListNode(int val) {
13+
this.val = val;
14+
}
15+
16+
ListNode(int val, ListNode next) {
17+
this.val = val;
18+
this.next = next;
19+
}
20+
}
21+
22+
class Solution {
23+
24+
public void reorderList(ListNode head) {
25+
// ํ’€์ด: ์—ญ์ˆœ์œผ๋กœ ์ €์žฅํ•  ์Šคํƒ์— node๋“ค์„ ๋„ฃ๊ณ , ๊ธฐ์กด node 1๊ฐœ/์Šคํƒ node 1๊ฐœ์”ฉ ์ด์–ด ๋ถ™์ธ๋‹ค
26+
// ์Šคํƒ์€ LIFO๋กœ ์ €์žฅ๋˜๊ธฐ ๋•Œ๋ฌธ์—, ๋ฌธ์ œ์—์„œ ์š”๊ตฌํ•˜๋Š” ์ˆœ์„œ๋Œ€๋กœ reorderList๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค
27+
// TC: O(N)
28+
// SC: O(2N)
29+
Stack<ListNode> stack = new Stack<>();
30+
31+
var curNode = head;
32+
while(curNode != null) {
33+
stack.push(curNode);
34+
curNode = curNode.next;
35+
}
36+
37+
curNode = head;
38+
var halfSize = stack.size() / 2; // ํ•œ๋ฒˆ์— 2๊ฐœ์”ฉ ์—ฐ๊ฒฐํ•˜๊ธฐ๋•Œ๋ฌธ์— ์ ˆ๋ฐ˜๊นŒ์ง€๋งŒ ๋Œ๋ฉด ๋จ
39+
for (int i=0; i<halfSize; i++) {
40+
var top = stack.pop();
41+
42+
var nextNode = curNode.next;
43+
curNode.next = top;
44+
top.next = nextNode;
45+
46+
curNode = nextNode;
47+
}
48+
49+
// ๋งŒ์•ฝ ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๊ฐ€ ํ™€์ˆ˜๋ฉด, ํ•˜๋‚˜์˜ ๋…ธ๋“œ๊ฐ€ ๋‚จ๊ธฐ ๋•Œ๋ฌธ์— next ๋…ธ๋“œ๋ฅผ null๋กœ ์ฒ˜๋ฆฌํ•ด์ค˜์•ผ ํ•œ๋‹ค.
50+
if (curNode != null) {
51+
curNode.next = null;
52+
}
53+
}
54+
}

0 commit comments

Comments
ย (0)