reorder list


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
public void (ListNode head) {
if (head == null || head.next == null)
return;

ListNode slow = head, fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode ptr = slow.next;
slow.next = null;
// reverse the second part
ListNode prev = null;
while (ptr != null) {
ListNode temp = ptr.next;
ptr.next = prev;
prev = ptr;
ptr = temp;
}
// combine the two
ListNode first = head, second = prev;
while (first != null && second != null) {
ListNode firstNext = first.next;
ListNode secondNext = second.next;
first.next = second;
second.next = firstNext;
first = firstNext;
second = secondNext;
}
}