• 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;
            }
        }
  • 相关阅读:
    让人耗尽脑汁的需求分析工作
    解读ASP.NET 5 & MVC6系列(1):ASP.NET 5简介
    WCF序列化与反序列化问题
    SQL存储过程调试
    MSSQL CharIndex()用法
    Erp:原料投入产出报表
    union all 简单用法
    带有游标的应用的存储过程
    SQL批量删除与批量插入
    表与表 不同条件下的关联SQL
  • 原文地址:https://www.cnblogs.com/skillking/p/9776154.html
Copyright © 2020-2023  润新知