Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-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}.
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head==null||head.next==null){
return;
}
ListNode slow=head;
ListNode fast=head.next;
//找到中点
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode after=slow.next;
slow.next=null;
ListNode pre=null;
//后半部分转置
while(after!=null){
ListNode tmp=after.next;
after.next=pre;
pre=after;
after=tmp;
}
//合并
ListNode first=head;
after=pre;
while(first!=null&&after!=null){
ListNode firstTmp=first.next;
ListNode afterTmp=after.next;
first.next=after;
first=firstTmp;
after.next=first;
after=afterTmp;
}
}
}