js实现队列的三种方法
使用数组实现队列
数组是最简单的队列实现方式,利用 push 和 shift 方法模拟队列的先进先出(FIFO)特性。

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

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






