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

/**
 * 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){
            return;
        }
        ListNode slow = head;
        ListNode fast = head;
        while(fast.next!=null && fast.next.next!=null){
            fast=fast.next.next;
            slow = slow.next;
        }
        
        ListNode after = slow.next;
        slow.next = null;
        ListNode pre = null;
        while(after!=null){
            ListNode temp = after.next;
            after.next = pre;
            pre = after;
            after = temp;
        }
        after = pre;
        ListNode first = head;
        while(after!=null){
            ListNode f = first.next;
            ListNode a = after.next;
            first.next=after;
            first=f;
            after.next = first;
            after = a;
        }
    }
}

 

posted @ 2019-07-25 16:30  紫色的雪  阅读(320)  评论(0)    收藏  举报