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;
            }
        }
    
  • 相关阅读:
    shell脚本的分发,测试,查看
    shell 脚本获取cpu信息(转载)
    shell 脚本编写之获取字符串长度(转载)
    service
    关于Linux安装中NAT模式和桥接模式的区别详解(转载)
    kdj
    pod 详解
    k8s基本概念,资源对象
    AliOS Things添加环境变量
    子函数通过一级指针访问二维数组
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/8919045.html
Copyright © 2011-2022 走看看