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 class Solution {
public ListNode reverse(ListNode head){
ListNode pre=null;
ListNode ruNode=head;
ListNode result=null;
while(ruNode!=null){
ListNode nextNode=ruNode.next;
if(nextNode==null){
result=ruNode;
}
ruNode.next=pre;
pre=ruNode;
ruNode=nextNode;
}
return result;
}
public void merge(ListNode l1,ListNode l2){
while(l1!=null){
ListNode l2next=l2.next;
ListNode l1next=l1.next;
l1.next=l2;
if (l1next== null)
break;//l2比l1长一个单位,l1到最后一个节点的时候,就可以退出merge过程了
l2.next=l1next;
l1=l1next;
l2=l2next;
}
}
public void reorderList(ListNode head) {
if(head==null||head.next==null) return;
ListNode slow=head;
ListNode fast=head;
ListNode pre=null;
while(fast!=null&&fast.next!=null){
pre=slow;
slow=slow.next;
fast=fast.next.next;
}
pre.next=null;
ListNode result2=reverse(slow);
merge(head,result2);
}
}