Skip to content

Commit d3ef7fd

Browse files
committed
add reorder list solution
1 parent f63ad48 commit d3ef7fd

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

reorder-list/Tessa1217.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
// 시간복잡도: O(n), 공간복잡도: O(1)
13+
public void reorderList(ListNode head) {
14+
15+
// Slow, Fast Pointer
16+
// 1 - 2 - 3 - 4 - 5
17+
ListNode slow = head;
18+
ListNode fast = head;
19+
20+
// fast가 끝까지 닿을 때 중점 찾기
21+
// slow = 3
22+
while (fast != null && fast.next != null) {
23+
slow = slow.next;
24+
fast = fast.next.next;
25+
}
26+
27+
28+
// 중간 이후부터 끝까지 (second half of list) => reverse order
29+
// 3 이후부터 -> 4 - 5
30+
// reverse - 5 - 4
31+
ListNode backHead = null; // second half of list's new head
32+
ListNode backSide = slow.next;
33+
slow.next = null;
34+
35+
while (backSide != null) {
36+
ListNode temp = backSide.next;
37+
backSide.next = backHead;
38+
backHead = backSide;
39+
backSide = temp;
40+
}
41+
42+
// Merge first and second half
43+
44+
// 1 - 2 - 3
45+
ListNode firstHalf = head;
46+
// 5 - 4
47+
ListNode secondHalf = backHead;
48+
49+
// 1 - 5 - 2 - 4 - 3
50+
while (secondHalf != null) {
51+
ListNode temp = firstHalf.next;
52+
firstHalf.next = secondHalf;
53+
firstHalf = secondHalf;
54+
secondHalf = temp;
55+
}
56+
}
57+
}
58+
59+

0 commit comments

Comments
 (0)