Skip to content

143. 重排链表 #40

@webVueBlog

Description

@webVueBlog

143. 重排链表

Description

Difficulty: 中等

Related Topics: , 递归, 链表, 双指针

给定一个单链表 L的头节点 head ,单链表 L 表示为:

L0 → L1 → … → Ln - 1 → Ln

请将其重新排列后变为:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

输入:head = [1,2,3,4]
输出:[1,4,2,3]

示例 2:

输入:head = [1,2,3,4,5]
输出:[1,5,2,4,3]

提示:

  • 链表的长度范围为 [1, 5 * 104]
  • 1 <= node.val <= 1000

Solution

Language: JavaScript

/**
 * 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.
 */
// 利用双向队列依次弹出前后对应的节点并进行插入操作
// 首先遍历将链表每一项放入队列
// 每次弹出队列头和队列尾的节点并改变指向
// 将尾节点(队列中的最后一个元素)的next赋值为null
var reorderList = function(head) {
    if (head === null) return head
    let queue = []
    let p = head
    while (p) {
        queue.push(p)
        p = p.next
    }
    while (queue.length > 2) {
        let h = queue.shift()
        let t = queue.pop()
        t.next = h.next
        h.next = t
    }
    queue[queue.length-1].next = null
    return head
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions