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

Given a singly linked list LL 0L 1→…→L n-1L n,
reorder it to: L 0L n L 1L n-1L 2L 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;
     while (fast.next!= null &&fast.next.next!= null ){
         slow=slow.next;
         fast=fast.next.next;
     }
      ListNode preMiddle=slow;   
     ListNode precurr=slow.next;
     while (precurr.next!= null ){
         ListNode current=precurr.next;
         precurr.next=current.next;
         current.next=preMiddle.next;
         preMiddle.next=current;
     }
         slow=head;
         fast=preMiddle.next;
     while (slow!=preMiddle){
          preMiddle.next=fast.next;
                 fast.next=slow.next;
                 slow.next=fast;
                 slow=fast.next;
                 fast=preMiddle.next;
     }
     }
}

猜你喜欢

转载自blog.csdn.net/boguesfei/article/details/80473912