forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimsosleepy.java
63 lines (54 loc) ยท 1.73 KB
/
imsosleepy.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
55
56
57
58
59
60
61
62
63
// GPT์ ๋์์ ๋ฐ์ ์กฐ๊ธ ๋ ๊ณต๊ฐ๋ณต์ก๋๊ฐ ๋ฎ๊ณ ๋น ๋ฅธ ๋ฐฉ์์ผ๋ก ๊ตฌํ
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null) return;
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode second = reverse(slow.next);
slow.next = null;
ListNode first = head;
while (second != null) {
ListNode tmp1 = first.next;
ListNode tmp2 = second.next;
first.next = second;
second.next = tmp1;
first = tmp1;
second = tmp2;
}
}
private ListNode reverse(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}
// ์ฒซ๋ฒ์งธ ์๊ฐํ ํ์ด๋ฐฉ์ ๋ฆฌ์คํธ๋ฅผ ๋ง๋ค๊ณ ๊ฐ์ ๋ฃ์ด์ ์ฒ๋ฆฌํ๋ ์๊ฐ๋ณต์ก๋๋ O(N)์ผ๋ก ์ด๋ก ์ ๊ฐ์ผ๋
// ์๋๋ผ ํ๊ท ์๋๋ณด๋ค ํ์ ํ๊ฒ ๋ฎ๊ฒ๋์จ๋ค.
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null) return;
List<ListNode> list = new ArrayList<>();
ListNode temp = head;
while (temp != null) {
list.add(temp);
temp = temp.next;
}
int i = 0, j = list.size() - 1;
while (i < j) {
list.get(i).next = list.get(j);
i++;
if (i == j) break;
list.get(j).next = list.get(i);
j--;
}
list.get(i).next = null;
}
}