zoukankan      html  css  js  c++  java
  • Reorder List

    2018-04-23 14:34:09

    一、Odd Even Linked List

    问题描述:

    问题求解:

    如果思考从swap角度来解决问题就会陷入一个误区,其实直接使用链表的指针分别构造出odd和even即可。

        public ListNode oddEvenList(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode odd = head, even = head.next, evenHead = even;
            while (even != null && even.next != null) {
                odd.next = odd.next.next;
                even.next = even.next.next;
                odd = odd.next;
                even = even.next;
            }
            odd.next = evenHead;
            return head;
        }
    

    二、Reorder List

    问题描述:

    问题求解:

    step1:找到中点

    step2:把后半段反转,使用插入法

    step3:然后开始执行一轮的插入操作

        public void reorderList(ListNode head) {
            if (head == null || head.next == null) return;
            ListNode slow = head, fast = head;
            while (fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
            }
            ListNode cur = slow.next;
            ListNode then = null;
            while (cur != null && cur.next != null) {
                then = cur.next;
                cur.next = then.next;
                then.next = slow.next;
                slow.next = then;
            }
            cur = head;
            while (slow.next != null) {
                ListNode tmp = cur.next;
                ListNode toInsert = slow.next;
                slow.next = toInsert.next;
                toInsert.next = cur.next;
                cur.next = toInsert;
                cur = tmp;
            }
        }
    
  • 相关阅读:
    JAVA中==与equals的区别
    spring面试重点
    struts2
    每个新手程序员必看的 SQL 指南
    QueryRunner的使用
    jquery GET POST
    jquery添加元素
    jquery 滑动动画
    jdbc 安装驱动
    为什么做java的web开发我们会使用struts2,springMVC和spring这样的框架?
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/8919045.html
Copyright © 2011-2022 走看看