美文网首页
leetcode-day8-重排链表[143题]

leetcode-day8-重排链表[143题]

作者: 孙静静 | 来源:发表于2020-10-20 11:03 被阅读0次
image.png

思路: 定义一个可双向出节点的队列,将链表遍历进去,这样的话,队列就是[1,2,3,4,5], 然后依次出1,5,再是2,4,最后是3,也就是先出队列的头节点和尾节点,然后连接,这里最重要的是,不要忘记5和2的连接。

/**
 * 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 === null) return null;
    let node = head;
    let queue = []; // 定义一个可以双向出节点的队列
    while(node){ // 将链表中元素加入队列中
        queue.push(node);
        node = node.next;
    }
    while(queue.length > 0){ 
        let shift_node = queue.shift();  // 头部节点
        let pop_node = queue.pop(); // 尾部节点
        if(pop_node){ // 如果链表节点为奇数个数,则最后一个无pop节点
            shift_node.next = pop_node; // 头节点的下一个节点指向尾节点
            pop_node.next = queue.length ? queue[0] : null; // 交换节点后,让队列中开始的尾节点指向原有链表的下一个节点,这步很重要
        } else {
            shift_node.next = null;
        }
        
    }
    return head;
};

相关文章

  • leetcode-day8-重排链表[143题]

    思路: 定义一个可双向出节点的队列,将链表遍历进去,这样的话,队列就是[1,2,3,4,5], 然后依次出1,5,...

  • 143. 重排链表

    143. 重排链表

  • leetcode链表之重排链表

    143、重排链表[https://leetcode-cn.com/problems/reorder-list/] ...

  • LeetCode 第143题:重排链表

    1、前言 2、思路 使用栈存储。 3、代码

  • 143. 重排链表

    给定一个单链表 L:L0→L1→…→Ln-1→Ln ,将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln...

  • 143. 重排链表

    题目地址 1.想法 1.从题目的题意可知,我们需要三步, step 1:将现有的链表分成两个部分1.L0→L中 2...

  • 143. 重排链表

    143. 重排链表 给定一个单链表 L:L0→L1→…→Ln-1→Ln ,将其重新排列后变为: L0→Ln→L1→...

  • LeetCode - #143 重排链表

    前言 我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swi...

  • 【2019-08-21】leetcode(141-150)

    141、环形链表 142、环形链表II 143、重排链表 144、二叉树的前序遍历 145、二叉树后序遍历 146...

  • T143、链表重排

    给定一个单链表 L:L0→L1→…→Ln-1→Ln ,将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln...

网友评论

      本文标题:leetcode-day8-重排链表[143题]

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