143.Reorder List
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
public void reorderList(ListNode head) {
if (head == null || head.next == null)
return;
//找到链表的中点,如1 2 3 4 5 6 7 8,则p1是4
ListNode p1 = head;
ListNode p2 = head;
while (p2.next != null && p2.next.next != null) {
p1 = p1.next;
p2 = p2.next.next;
}
//链表后半边逆序,5 6 7 8 变成 8 7 6 5
ListNode middle = p1; //middle 是4
ListNode temp = p1.next; //temp 是5
middle.next = reverse(temp);
//达到最后排序目的
p1 = head;
p2 = middle.next;
while (p1 != middle) {
middle.next = p2.next; //另4->7
p2.next = p1.next; //8->2
p1.next = p2;//1->8
p1 = p2.next;//让p1等于2
p2 = middle.next; //p2等于7,现在链表1 8 2 3 4 7 6 5
}
}
private ListNode reverse(ListNode head) {
ListNode dummy = new ListNode(-1);
ListNode sec = null;
while (head != null) {
sec = head.next;
head.next = dummy.next;
dummy.next = head;
head = sec;
}
return dummy.next;
}