143. Reorder List

一、题目

  1、审题

  

  2、分析

    给出一个单向链表,将其重新排序,排序规则如上。

二、解答

  1、思路:

    方法一、

      观察上边的重新排序后的链表。可以分为三个步骤。

      ①、找到中间节点;

      ②、将后边部分的链表进行翻转。

      ③、在前边部分的链表中间隔插入后边部分链表的一个节点。

    public void reorderList(ListNode head) {
        if(head == null || head.next == null)
            return;
        
        ListNode walker = head;
        ListNode runner = head;
        // 1、find Mid
        while(runner.next != null && runner.next.next != null) {
            walker = walker.next;
            runner = runner.next.next;
        }
        ListNode midNode = walker;
        
        // 2、 reverse post
        ListNode pre = midNode.next;
        
        midNode.next = null;
        
        ListNode next = null;
        if(pre.next != null)
            next = pre.next;
        pre.next = null;
        
        while(pre != null && next != null) {
            ListNode nextAndNext = next.next;
            next.next = pre;
            pre = next;
            next = nextAndNext;
        }
        
        // 3、 insert nodes
        ListNode next2 = null;
        while(head != null && pre != null) {
            next = head.next;
            next2 = pre.next;
            
            head.next = pre;
            pre.next = next;
            
            head = next;
            pre = next2;
        }
    }
原文地址:https://www.cnblogs.com/skillking/p/9776154.html