File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments