zoukankan      html  css  js  c++  java
  • 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;
            }
        }
  • 相关阅读:
    DFS初级算法题练习 POJ2488 POJ3009 POJ1088
    分支限界法基础练习笔记
    PuyoPuyo DFS算法练习
    回溯法基础练习笔记
    java基础:I/O流学习笔记
    synchronized锁的各种用法及注意事项
    20.04搭建ROS2
    西安 交建交通科技 招聘信息
    在.NET2.0中使用LINQ
    sqlite+VS2010+EF
  • 原文地址:https://www.cnblogs.com/skillking/p/9776154.html
Copyright © 2011-2022 走看看