Reorder List

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (head==null || head.next==null){
            return;
        }
        ListNode p1 = head;
        ListNode temp = null;
        ListNode p2 = null,p=null;
        int len=0,i=0;
        //求长度
        while (p1!=null) {
            p1 = p1.next;
            len++;
        }
        //把p移动到一半位置
        p = head;
        while (p !=null && i<len/2-1) {
            p = p.next;
            i++;
        }
        //把后半部分逆序排列
        p1 = p.next.next;
        p2 = p.next;
        p2.next = null;
        while (p1 !=null) {
            temp = p1.next;
            p1.next = p2;
            p2 = p1;
            p1 = temp;
        }
        p.next = p2;
        p = p.next;
        //从head重新组织
        p1 = head;
        ListNode p1n = null,pn=null;
        ListNode pstop=p;
        while(p.next!=null){
            pn = p.next;
            p1n = p1.next;
            p.next = p1.next;
            p1.next = p;
            p = pn;
            p1 = p1n;
            if (p1.next==pstop){
                p1.next = p;
                break;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/23lalala/p/3506833.html