You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS链表实现队列异常:deque后peek返回结果不符合预期

问题原因分析

你的队列实现问题出在enqueue方法的逻辑错误,导致链表结构出现重复节点,最终deque后head没有正确指向预期的元素。

具体错误点

在enqueue方法中,当队列为空(!this.tail)时,你重新创建了一个新的对象{value: item}赋值给head和tail,但之前已经创建了node变量。后续代码又执行了this.tail.next = node和this.tail = node,这就导致第一个元素被重复创建,链表结构混乱:

enqueue(item){
    const node = {value: item} // 创建了一个节点
    this.length++
    if (!this.tail){
        // 这里错误地重新创建了一个新节点,而非使用上面的node
        this.tail = this.head = {value: item}
    }

    this.tail.next = node // 把新node挂到tail后面
    this.tail = node // 更新tail为新node
}

以你测试流程为例:

  1. 第一次enqueue('rawr')后,链表变成:{value: 'rawr'}(head) → {value: 'rawr'}(node,tail)
  2. 第二次enqueue('meow')后,链表变成:{value: 'rawr'}(head) → {value: 'rawr'} → {value: 'meow'}(tail)
  3. 执行deque()时,移除的是第一个{value: 'rawr'}节点,此时head指向第二个{value: 'rawr'}节点,所以peek()返回rawr而非预期的meow。
修复方案

修改enqueue方法的if分支,直接使用预先创建的node,同时避免空队列时执行多余的后续操作:

enqueue(item){
    const node = {value: item}
    this.length++
    if (!this.tail){
        // 使用已创建的node赋值给head和tail
        this.tail = this.head = node
        return
    }

    this.tail.next = node
    this.tail = node
}

或者用else包裹后续代码:

enqueue(item){
    const node = {value: item}
    this.length++
    if (!this.tail){
        this.tail = this.head = node
    } else {
        this.tail.next = node
        this.tail = node
    }
}

修复后,测试流程的链表结构就会正常:

  1. enqueue('rawr'):head和tail都指向{value: 'rawr'}
  2. enqueue('meow'):tail的next指向{value: 'meow'},tail更新为这个新节点
  3. deque()移除rawr节点,head指向meow节点,peek()返回meow,符合预期。

内容的提问来源于stack exchange,提问作者ian.thecheesestomper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 14:25:25