当前位置:首页 > JavaScript

js实现队列的三种方法

2026-03-02 03:27:57JavaScript

使用数组实现队列

数组是最直观的队列实现方式,利用pushshift方法分别模拟入队和出队操作。

const queue = [];
queue.push(1); // 入队
queue.push(2);
const item = queue.shift(); // 出队,返回1

缺点shift操作的时间复杂度为O(n),因为需要移动剩余元素。

使用链表实现队列

链表结构天然适合队列操作,通过维护头尾指针实现O(1)时间复杂度的入队和出队。

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

class Queue {
  constructor() {
    this.head = null;
    this.tail = null;
    this.size = 0;
  }

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

  dequeue() {
    if (!this.head) return null;
    const value = this.head.value;
    this.head = this.head.next;
    this.size--;
    return value;
  }
}

使用两个栈实现队列

通过维护输入栈和输出栈,将栈的LIFO特性转换为队列的FIFO特性。

js实现队列的三种方法

class StackQueue {
  constructor() {
    this.inStack = [];
    this.outStack = [];
  }

  enqueue(value) {
    this.inStack.push(value);
  }

  dequeue() {
    if (this.outStack.length === 0) {
      while (this.inStack.length > 0) {
        this.outStack.push(this.inStack.pop());
      }
    }
    return this.outStack.pop();
  }
}

特点:摊还时间复杂度为O(1),适合需要兼顾栈和队列操作的场景。

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

相关文章

uniapp队列下载

uniapp队列下载

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

php数组实现队列

php数组实现队列

使用数组实现队列的基本方法 在PHP中,数组可以模拟队列的先进先出(FIFO)特性。通过内置的数组函数,可以轻松实现队列的基本操作。 初始化队列 $queue = []; 入队操作(enqueue…

js 实现一个并发队列

js 实现一个并发队列

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

js实现队列的三种方法

js实现队列的三种方法

数组实现队列 使用数组的 push 和 shift 方法模拟队列的先进先出特性。 class ArrayQueue { constructor() { this.items = []…

js队列实现

js队列实现

队列的基本概念 队列是一种先进先出(FIFO)的数据结构,支持在队尾添加元素(入队),在队头移除元素(出队)。JavaScript中可通过数组或链表实现队列。 基于数组的实现 利用数组的push和s…

js 实现队列

js 实现队列

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