当前位置:首页 > 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),频繁出队时性能较差。

链表实现队列

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

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)。

双栈实现队列

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

js实现队列的三种方法

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),适合需要兼顾入队和出队性能的场景。

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

相关文章

Vue消息队列实现

Vue消息队列实现

Vue 消息队列实现方法 在 Vue 中实现消息队列可以通过多种方式,以下是几种常见的方法: 使用 Vuex 状态管理 Vuex 可以用于管理全局状态,适合实现消息队列功能。通过 mutations…

js 实现一个任务队列

js 实现一个任务队列

实现基础任务队列结构 使用数组存储任务,通过push方法添加任务,shift方法取出任务执行: class TaskQueue { constructor() { this.tasks…

js队列实现

js队列实现

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

java队列如何使用

java队列如何使用

Java队列的基本使用 Java提供了多种队列实现,包括LinkedList、ArrayDeque、PriorityQueue等。队列通常遵循先进先出(FIFO)原则,但某些实现(如PriorityQ…

java如何使用队列

java如何使用队列

队列的基本概念 队列是一种先进先出(FIFO)的数据结构,常用于任务调度、缓冲处理等场景。Java中可通过java.util.Queue接口及其实现类(如LinkedList、ArrayDeque)来…