当前位置:首页 > JavaScript

js实现队列的三种方法

2026-04-05 04:20:29JavaScript

使用数组实现队列

数组是最简单的队列实现方式,利用 pushshift 方法模拟队列的先进先出(FIFO)特性。

js实现队列的三种方法

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)),enqueuedequeue 均为 O(1)。

js实现队列的三种方法

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

class LinkedListQueue {
  constructor() {
    this.front = null;
    this.rear = null;
    this.size = 0;
  }

  enqueue(value) {
    const newNode = new Node(value);
    if (this.rear === null) {
      this.front = newNode;
      this.rear = newNode;
    } else {
      this.rear.next = newNode;
      this.rear = newNode;
    }
    this.size++;
  }

  dequeue() {
    if (this.front === null) return null;
    const removedValue = this.front.value;
    this.front = this.front.next;
    if (this.front === null) this.rear = null;
    this.size--;
    return removedValue;
  }

  peek() {
    return this.front?.value;
  }

  isEmpty() {
    return this.size === 0;
  }
}

使用两个栈实现队列

通过两个栈(输入栈和输出栈)模拟队列行为,enqueue 直接压入输入栈,dequeue 时从输出栈弹出。

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

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

相关文章

php 锁 三种实现

php 锁 三种实现

PHP 锁的三种实现方式 文件锁(flock) 文件锁通过 flock() 函数实现,适用于单机环境下的进程同步。 $fp = fopen("lockfile.lock", "w+"); if…

php 队列实现

php 队列实现

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

js 实现异步队列

js 实现异步队列

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

js 实现一个并发队列

js 实现一个并发队列

实现并发队列的基本思路 在JavaScript中实现并发队列,通常需要控制同时执行的异步任务数量。可以通过队列管理待执行任务,并结合Promise和计数器实现并发控制。 基于Promise的并发队列…

js 实现队列

js 实现队列

队列的基本概念 队列是一种先进先出(FIFO)的数据结构,支持从尾部插入元素(入队)和从头部移除元素(出队)。以下是 JavaScript 中实现队列的几种方法。 使用数组实现队列 数组…

js 实现消息队列

js 实现消息队列

实现消息队列的基本概念 消息队列是一种异步通信机制,允许不同的应用程序或组件通过发送和接收消息来交互。在JavaScript中,可以使用数组、对象或第三方库来实现消息队列的功能。 使用数组实现简单消…