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;
            }
        }
    
  • 相关阅读:
    3、选择排序(最小值/最大值)
    2、冒泡排序
    1、快速排序
    Stream操作
    1. 两数之和
    Mysql修改字段类型修改
    获取节假日
    mysql 前缀 + 编号 补0
    一口气说出 6种@Transactional注解的失效场景
    Activiti最全入门教程(基于Eclipse插件开发)
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/8919045.html
Copyright © 2011-2022 走看看