143. Reorder List

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
class Solution {
public void reorderList(ListNode head) {
ListNode dummyHead = new ListNode(-1, head);
ListNode fast = dummyHead, slow = dummyHead;

// d -> 1 -> 2 -> 3 -> 4
// f
// s
// f
// s
// f
// s

while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}

ListNode rightHead = slow.next;
slow.next = null;

rightHead = reverse(rightHead);
ListNode nodeA = head, nodeB = rightHead;
while (nodeB != null) {
ListNode nextA = nodeA.next;
ListNode nextB = nodeB.next;

nodeA.next = nodeB;
nodeB.next = nextA;

nodeA = nextA;
nodeB = nextB;
}
}

private ListNode reverse(ListNode head) {
ListNode pre = null, curr = head;

while (curr != null) {
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}

return pre;
}
}

References

143. Reorder List
剑指 Offer II 026. 重排链表