• 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;
            }
        }
    
  • 相关阅读:
    51nod1089(最长回文子串之manacher算法)
    51nod1088(最长回文子串)
    51nod1256(乘法逆元)
    51nod1085(01背包)
    51nod1079(中国剩余定理)
    数据的特征工程
    30种提高mysql处理速度的方法
    机器学习资料
    python3.6安装-windows
    python import sklearn出错 "ImportError: DLL load failed: 找不到指定的模块。
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/8919045.html
Copyright © 2020-2023  润新知