143 Reorder List 重排链表

给定一个单链表L:L0→L1→…→Ln-1→Ln,
重新排列后为: L0→Ln→L1→Ln-1→L2→Ln-2→…
必须在不改变节点的值的情况下进行原地操作。
例如,
给定链表 {1,2,3,4},按要求重排后为 {1,4,2,3}。
详见:https://leetcode.com/problems/reorder-list/description/

Java实现:

1、使用快慢指针来找到链表的中点,并将链表从中点处断开,形成两个独立的链表;
2、将第二个链翻转;
3、将第二个链表的元素间隔地插入第一个链表中。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        if(head==null||head.next==null){
            return;
        }
        ListNode slow=head;
        ListNode fast=head;
        while(fast!=null&&fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        fast=slow.next;
        slow.next=null;
        ListNode pre=null;
        ListNode next=null;
        while(fast!=null){
            next=fast.next;
            fast.next=pre;
            pre=fast;
            fast=next;
        }
        slow=head;
        fast=pre;
        ListNode post1=null;
        ListNode post2=null;
        while(slow!=null&&fast!=null){
            post1=slow.next;
            post2=fast.next;
            slow.next=fast;
            fast.next=post1;
            slow=post1;
            fast=post2;
        }
    }
}

参考:https://www.cnblogs.com/grandyang/p/4254860.html

原文地址:https://www.cnblogs.com/xidian2014/p/8727170.html