forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTonyKim9401.java
34 lines (30 loc) ยท 870 Bytes
/
TonyKim9401.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
// TC: O(n)
// -> find middle, reverse, merge -> max O(n)
// SC: O(1)
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 backSide = null;
ListNode curr = slow.next;
slow.next = null;
while (curr != null) {
ListNode temp = curr.next;
curr.next = backSide;
backSide = curr;
curr = temp;
}
ListNode first = head;
ListNode second = backSide;
while (second != null) {
ListNode temp = first.next;
first.next = second;
first = second;
second = temp;
}
}
}