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}
.
find the mid point of the list, reverse the list from midNext -> end.
break the list into to part, head-mid | midNext - end;
Insert the node in the second part into the first part one by one.
public void reorderList(ListNode head) {
if(head == null || head.next==null)
return;
ListNode slow = head, fast = head;
while(fast.next != null&&fast.next.next!=null){
slow = slow.next;
fast = fast.next.next;
}
fast = reverse(slow.next);
slow.next = null;
slow=head;
ListNode slowNext=null, fastNext=null;
while(fast!=null){
slowNext = slow.next;
fastNext = fast.next;
slow.next=fast;
fast.next=slowNext;
slow = slowNext;
fast = fastNext;
}
}
public ListNode reverse(ListNode head){
ListNode slow = head, run = head.next;
while(run!=null){
slow.next=run.next;
run.next=head;
head=run;
run=slow.next;
}
return head;
}