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)
return;
ListNode slow = head;
ListNode fast = head;
//找到链表的中点,如1 2 3 4 5 6 7 8,则slow是4
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//链表后半边逆序,5 6 7 8 变成 8 7 6 5
ListNode secMiddle = slow; //secMiddle:4
ListNode secCur = reverse(slow.next);
secMiddle.next = secCur;
slow = head;//slow:1
fast = secCur;//fast:8
while (slow != secMiddle) {
secMiddle.next = fast.next;//4->7
fast.next = slow.next;//8->2
slow.next = fast;//1->8
fast = secMiddle.next;//fast:7
slow = slow.next.next;//slow:2,现在链表:1 8 2 3 4 7 6 5
}
}
private ListNode reverse(ListNode head) {
if (head == null)
return null;
ListNode dummy = new ListNode(-1);
ListNode second = null;
while (head != null) {
second = head.next;
head.next = dummy.next;
dummy.next = head;
head = second;
}
return dummy.next;
}
浙公网安备 33010602011771号