reorder-list

题目描述

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 fast=head;
        ListNode slow=head;
        while (fast.next!=null&&fast.next.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
        //从中间拆分链表
        ListNode right=slow.next;
        slow.next=null;
        //翻转后半部分链表
        ListNode pre=null;
        while (right!=null){
            ListNode temp = right.next;
            right.next=pre;
            pre=right;
            right=temp;
        }
        //合并链表
        ListNode left = head;
        right = pre;
        while (left!=null&&right!=null){
            ListNode lTemp=left.next;
            ListNode rTemp=right.next;
            left.next=right;
            left=lTemp;
            right.next=left;
            right=rTemp;
        }
    }
}