当前位置:首页 > JavaScript

js实现反向队列

2026-04-07 15:21:44JavaScript

使用数组实现反向队列

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

js实现反向队列

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];
  }
}

使用链表实现反向队列

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

js实现反向队列

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),适合高频操作场景。

实际应用示例

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实现动画

使用 CSS 动画与 JavaScript 控制 通过 JavaScript 动态添加或移除 CSS 类来触发动画。CSS 定义关键帧(@keyframes),JavaScript 通过 classL…

vue实现队列

vue实现队列

Vue 实现队列功能 在 Vue 中实现队列功能,可以利用数组的 push 和 shift 方法模拟队列的先进先出(FIFO)特性。以下是一个简单的实现示例: <template>…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

php 实现队列

php 实现队列

PHP 实现队列的方法 PHP 可以通过多种方式实现队列功能,以下是几种常见的实现方法: 使用数组实现队列 PHP 数组可以通过 array_push 和 array_shift 函数模拟队列的先进…

js实现变形

js实现变形

使用 CSS 和 JavaScript 实现元素变形 在 JavaScript 中实现变形效果通常结合 CSS 的 transform 属性,通过动态修改该属性实现元素的旋转、缩放、倾斜或平移。 基…