zoukankan      html  css  js  c++  java
  • 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;
      }
    };

  • 相关阅读:
    nginx的优化
    apache日志轮询技术
    PV IP UV的概念介绍
    日志文件记录的重要性
    linux chmod 755
    ssh免密码登录机器(使用公钥和秘钥进行加密来实现)
    ffmpeg基础
    linux使用grep和find查找内容
    为什么我们会越来越穷?
    从我干程序员开始 我就不准备干这个行业
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/10204388.html
Copyright © 2011-2022 走看看