当前位置:首页 > 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 队列实现方法 PHP 队列实现可以通过多种方式完成,以下是几种常见的方法: 使用数据库实现队列 创建数据库表存储队列任务,包含字段如 id, payload, status, create…

php 实现消息队列

php 实现消息队列

PHP 实现消息队列的方法 使用 Redis 实现消息队列 Redis 的 List 结构可以用于实现简单的消息队列。通过 LPUSH 和 RPOP 命令可以实现先进先出的队列。 $redis =…

php 锁 三种实现

php 锁 三种实现

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

php如何实现队列

php如何实现队列

PHP 实现队列的方法 使用数组模拟队列 PHP 数组可以模拟队列的先进先出(FIFO)特性。array_push 用于入队,array_shift 用于出队。 $queue = []; array…

js实现队列

js实现队列

队列的基本概念 队列是一种遵循先进先出(FIFO)原则的线性数据结构。元素从队尾入队,从队头出队,操作包括enqueue(入队)、dequeue(出队)、peek(查看队头元素)和isEmpty(判断…

js 实现消息队列

js 实现消息队列

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