当前位置:首页 > JavaScript

js实现反向队列

2026-04-07 15:21:44JavaScript

使用数组实现反向队列

JavaScript中可以通过数组的push()shift()方法实现队列,反向队列则可以使用unshift()pop()方法。

class ReverseQueue {
  constructor() {
    this.items = [];
  }

  enqueue(element) {
    this.items.unshift(element);
  }

  dequeue() {
    if (this.isEmpty()) return "Underflow";
    return this.items.pop();
  }

  isEmpty() {
    return this.items.length === 0;
  }

  front() {
    if (this.isEmpty()) return "No elements in Queue";
    return this.items[this.items.length - 1];
  }
}

使用链表实现反向队列

链表实现反向队列需要维护头尾指针,入队操作在头部插入,出队操作从尾部移除。

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class ReverseQueue {
  constructor() {
    this.head = null;
    this.tail = null;
  }

  enqueue(value) {
    const newNode = new Node(value);
    if (!this.head) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      newNode.next = this.head;
      this.head = newNode;
    }
  }

  dequeue() {
    if (!this.head) return null;
    if (this.head === this.tail) {
      const value = this.head.value;
      this.head = null;
      this.tail = null;
      return value;
    }
    let current = this.head;
    while (current.next !== this.tail) {
      current = current.next;
    }
    const value = this.tail.value;
    this.tail = current;
    this.tail.next = null;
    return value;
  }
}

性能比较

数组实现的优点是代码简洁,但在频繁操作时可能遇到性能问题,因为unshift()pop()操作的时间复杂度在最坏情况下是O(n)。

链表实现虽然代码复杂,但所有操作的时间复杂度都是O(1),适合高频操作场景。

js实现反向队列

实际应用示例

const rq = new ReverseQueue();
rq.enqueue(10);
rq.enqueue(20);
rq.enqueue(30);
console.log(rq.dequeue()); // 输出10
console.log(rq.dequeue()); // 输出20

反向队列常用于需要后进先出但又需要队列接口的场景,如某些消息处理系统或特殊算法实现。

标签: 队列js
分享给朋友:

相关文章

js实现吸色

js实现吸色

使用Canvas实现吸色功能 通过Canvas的getImageData方法获取像素颜色数据。创建一个Canvas元素,将目标图像绘制到Canvas上,通过鼠标事件获取坐标对应的颜色值。 c…

js 实现滚动

js 实现滚动

实现滚动的方法 使用 window.scrollTo() window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。 // 滚动到指定位…

js实现 拖动

js实现 拖动

实现拖动的步骤 HTML 结构 创建一个可拖动的元素和一个放置区域: <div id="draggable" draggable="true">拖动我</div> <d…

php 消息队列 实现

php 消息队列 实现

PHP 消息队列实现方法 使用 Redis 实现消息队列 Redis 的 LPUSH 和 BRPOP 命令可以轻松实现消息队列功能。生产者通过 LPUSH 将消息推入队列,消费者通过 BRPOP 阻…

js实现截图

js实现截图

使用HTML2Canvas库实现截图 HTML2Canvas是一个流行的JavaScript库,可以将网页元素或整个页面转换为Canvas图像。安装方式: npm install html2canv…

js实现同步

js实现同步

同步与异步的概念 在JavaScript中,同步代码会按照顺序执行,每一行代码必须等待上一行代码执行完成后才能运行。异步代码则允许在等待某些操作(如网络请求)完成的同时继续执行其他代码。 实现同步的…