-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_143.java
More file actions
39 lines (35 loc) · 1.06 KB
/
Copy pathP_143.java
File metadata and controls
39 lines (35 loc) · 1.06 KB
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
package leetcode.medium;
import utils.DataStructures.ListNode;
@SuppressWarnings({ "TailRecursion", "ConstantConditions" })
public class P_143 {
public void reorderList(ListNode head) {
final ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode upper = head;
ListNode slow = dummy;
ListNode fast = dummy;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode lower = slow.next;
slow.next = null;
lower = reverse(lower, null);
while (lower != null) {
final ListNode t1 = upper.next;
final ListNode t2 = lower.next;
upper.next = lower;
lower.next = t1;
upper = t1;
lower = t2;
}
}
private static ListNode reverse(ListNode head, ListNode newTail) {
if (head == null) {
return newTail;
}
final ListNode next = head.next;
head.next = newTail;
return reverse(next, head);
}
}