forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjaejeong1.java
54 lines (42 loc) ยท 1.24 KB
/
jaejeong1.java
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
52
53
54
import java.util.Stack;
// Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
public void reorderList(ListNode head) {
// ํ์ด: ์ญ์์ผ๋ก ์ ์ฅํ ์คํ์ node๋ค์ ๋ฃ๊ณ , ๊ธฐ์กด node 1๊ฐ/์คํ node 1๊ฐ์ฉ ์ด์ด ๋ถ์ธ๋ค
// ์คํ์ LIFO๋ก ์ ์ฅ๋๊ธฐ ๋๋ฌธ์, ๋ฌธ์ ์์ ์๊ตฌํ๋ ์์๋๋ก reorderList๋ฅผ ๋ง๋ค ์ ์๋ค
// TC: O(N)
// SC: O(N)
Stack<ListNode> stack = new Stack<>();
var curNode = head;
while(curNode != null) {
stack.push(curNode);
curNode = curNode.next;
}
curNode = head;
var halfSize = stack.size() / 2; // ํ๋ฒ์ 2๊ฐ์ฉ ์ฐ๊ฒฐํ๊ธฐ๋๋ฌธ์ ์ ๋ฐ๊น์ง๋ง ๋๋ฉด ๋จ
for (int i=0; i<halfSize; i++) {
var top = stack.pop();
var nextNode = curNode.next;
curNode.next = top;
top.next = nextNode;
curNode = nextNode;
}
// ๋ง์ฝ ๋
ธ๋์ ๊ฐ์๊ฐ ํ์๋ฉด, ํ๋์ ๋
ธ๋๊ฐ ๋จ๊ธฐ ๋๋ฌธ์ next ๋
ธ๋๋ฅผ null๋ก ์ฒ๋ฆฌํด์ค์ผ ํ๋ค.
if (curNode != null) {
curNode.next = null;
}
}
}