美文网首页
143. Reorder List

143. Reorder List

作者: jluemmmm | 来源:发表于2021-10-04 11:25 被阅读0次

重排链表
L0 → L1 → … → Ln - 1 → Ln
重写为
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

寻找链表中点 + 链表逆序 + 合并链表

  • 时间复杂度O(n),空间复杂度O(1)
  • Runtime: 112 ms, faster than 55.22%
  • Memory Usage: 47.4 MB, less than 20.87%
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {void} Do not return anything, modify head in-place instead.
 */
var reorderList = function(head) {
  if (!head) return;
  let slow = head;
  let fast = head;
  while (fast && fast.next){
    slow = slow.next;
    fast = fast.next.next;
  }
  
  let prev = null;
  let cur = slow;
  while (cur) {
    let tmp = cur.next;
    cur.next = prev;
    prev = cur;
    cur = tmp;
  }
  
  let first = head;
  let second = prev;
  while (second.next) {
    let tmp = first.next;
    first.next = second;
    first = tmp;
    
    tmp = second.next;
    second.next = first;
    second = tmp
  }
};



相关文章

  • 143. Reorder List

    题目143. Reorder List Given a singly linked list L: L0→L1→…...

  • 143. Reorder List

    实在是太困了 看不下去这一题的指针,明早上看

  • 143. Reorder List

    题目分析 Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorde...

  • 143. Reorder List

    题目 Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder ...

  • 143. Reorder List

    分为以下几个步骤,1使用快慢指针找到中间节点,2翻转后半部分,3逐个插入节点。

  • 143. Reorder List

    Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it ...

  • 143. Reorder List

    题目描述:给链表如L: L0→L1→…→Ln-1→Ln,将其重新排序为L0→Ln→L1→Ln-1→L2→Ln-2→...

  • 143. Reorder List

    这题很简单,不过很容易出bug特别在merge的时候,所以一定要逻辑清楚,先写好框架

  • 143. Reorder List

    Example 1: Given 1->2->3->4, reorder it to 1->4->2->3.Exa...

  • 143. Reorder List

    重排链表L0 → L1 → … → Ln - 1 → Ln重写为L0 → Ln → L1 → Ln - 1 → L...

网友评论

      本文标题:143. Reorder List

      本文链接:https://www.haomeiwen.com/subject/ejwbnltx.html