• 143. Reorder List


    /**

    143. Reorder List

    https://leetcode.com/problems/reorder-list/description/

    * @param {ListNode} head
    * @return {void} Do not return anything, modify head in-place instead.
    */

    var reorderList = function (head) {
      if (head==null || head.next==null)
        return;
      //1.find the middle of list
      let middle = findMiddle(head);
      let secondHead = middle.next;
      
      middle.next = null;//断开中点和后一段
      //2.reserve it
      let reverseSecondHead = reverseLinkedList(secondHead);
      //3.merge two list by items one by one
      return mergeLinkedList(head,reverseSecondHead);
    };

    var findMiddle = function (head) {
      let slow = head, fast = head;
      while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
      }
      return slow;
    };

    var reverseLinkedList = function (head) {
      let prev = null;
      let next = null;
      let current = head;
      while (current != null) {
        next = current.next;
        current.next = prev;//point to prve
        prev = current;
        current = next;
      }
      return prev;
    };

    var mergeLinkedList = function (node1,node2) {
      //将第二个链表的元素间隔地插入第一个链表中
      let cur = node1;
      while (node2!=null){
        let temp = node2.next;
        node2.next = cur.next;
        cur.next = node2;
        cur = cur.next.next;
        node2 = temp;
      }
    };

  • 相关阅读:
    C++中类模板的概念和意义
    欢迎访问新博客aiyoupass.com
    P2327
    P2885
    P1968
    Link-Cut-Tree
    树的重心
    点分治笔记
    SPOJ 375
    树链剖分
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/10204388.html
Copyright © 2020-2023  润新知