当前位置:首页 > JavaScript

js实现队列的三种方法

2026-01-31 12:11:57JavaScript

数组实现队列

使用数组的 pushshift 方法模拟队列的先进先出特性。

class ArrayQueue {
  constructor() {
    this.items = [];
  }
  enqueue(element) {
    this.items.push(element);
  }
  dequeue() {
    return this.items.shift();
  }
  peek() {
    return this.items[0];
  }
  isEmpty() {
    return this.items.length === 0;
  }
  size() {
    return this.items.length;
  }
}

缺点shift() 操作的时间复杂度为 O(n),频繁出队时性能较差。

js实现队列的三种方法

链表实现队列

通过链表节点实现高效的头尾操作,避免数组的频繁位移。

js实现队列的三种方法

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

class LinkedListQueue {
  constructor() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }
  enqueue(value) {
    const node = new Node(value);
    if (!this.head) {
      this.head = node;
      this.tail = node;
    } else {
      this.tail.next = node;
      this.tail = node;
    }
    this.length++;
  }
  dequeue() {
    if (!this.head) return null;
    const value = this.head.value;
    this.head = this.head.next;
    this.length--;
    if (this.length === 0) this.tail = null;
    return value;
  }
  peek() {
    return this.head?.value;
  }
  isEmpty() {
    return this.length === 0;
  }
}

优点enqueuedequeue 的时间复杂度均为 O(1)。

双栈实现队列

利用两个栈模拟队列行为,通过反转栈顺序实现先进先出。

class StackQueue {
  constructor() {
    this.inStack = [];
    this.outStack = [];
  }
  enqueue(element) {
    this.inStack.push(element);
  }
  dequeue() {
    if (this.outStack.length === 0) {
      while (this.inStack.length > 0) {
        this.outStack.push(this.inStack.pop());
      }
    }
    return this.outStack.pop();
  }
  peek() {
    if (this.outStack.length === 0) {
      while (this.inStack.length > 0) {
        this.outStack.push(this.inStack.pop());
      }
    }
    return this.outStack[this.outStack.length - 1];
  }
  isEmpty() {
    return this.inStack.length === 0 && this.outStack.length === 0;
  }
}

特点:摊还时间复杂度为 O(1),适合需要兼顾入队和出队性能的场景。

标签: 三种队列
分享给朋友:

相关文章

uniapp队列下载

uniapp队列下载

uniapp 实现队列下载的方法 在 uniapp 中实现队列下载通常需要管理多个下载任务,确保它们按顺序执行。可以通过以下方法实现: 使用 Promise 和递归实现队列下载 定义一个下载队列数…

php 消息队列 实现

php 消息队列 实现

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

react实现消息队列

react实现消息队列

实现消息队列的基本思路 在React中实现消息队列通常需要结合状态管理工具(如Redux、Context API)或自定义Hook来管理消息的存储、消费和清理。消息队列的核心功能包括消息的入队、出队、…

php使用redis实现队列

php使用redis实现队列

PHP 使用 Redis 实现队列 Redis 是一个高性能的键值存储系统,支持多种数据结构,如字符串、哈希、列表、集合等。利用 Redis 的列表(List)数据结构可以轻松实现队列功能。以下是实现…

php 队列实现

php 队列实现

使用数据库实现队列 在PHP中可以通过数据库表模拟队列行为,创建包含id、data、status和created_at字段的表。插入数据时状态设为pending,消费时更新为processing,完成…

js 实现异步队列

js 实现异步队列

异步队列的实现方法 在 JavaScript 中,实现异步队列可以通过多种方式,以下是几种常见的方法: 使用 Promise 链式调用 通过 Promise 的链式调用可以确保异步任务按顺序执行。每…