js实现队列
队列的基本概念
队列是一种遵循先进先出(FIFO)原则的数据结构。元素从队尾入队,从队头出队。JavaScript中可通过数组或链表实现队列。
基于数组的实现
利用数组的push和shift方法模拟队列操作,但shift操作的时间复杂度为O(n),可能影响性能。
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;
}
clear() {
this.items = [];
}
}
基于链表的实现
链表实现可避免数组shift的性能问题,每个节点存储值和指向下一个节点的引用。
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 newNode = new Node(value);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
}
dequeue() {
if (!this.head) return null;
const removedNode = this.head;
this.head = this.head.next;
if (!this.head) this.tail = null;
this.length--;
return removedNode.value;
}
peek() {
return this.head?.value;
}
isEmpty() {
return this.length === 0;
}
size() {
return this.length;
}
clear() {
this.head = null;
this.tail = null;
this.length = 0;
}
}
循环队列的实现
循环队列通过固定大小的数组和指针优化空间利用率,避免数据搬移。

class CircularQueue {
constructor(k) {
this.size = k;
this.queue = new Array(k);
this.head = -1;
this.tail = -1;
}
enqueue(value) {
if (this.isFull()) return false;
if (this.isEmpty()) this.head = 0;
this.tail = (this.tail + 1) % this.size;
this.queue[this.tail] = value;
return true;
}
dequeue() {
if (this.isEmpty()) return false;
if (this.head === this.tail) {
this.head = -1;
this.tail = -1;
} else {
this.head = (this.head + 1) % this.size;
}
return true;
}
Front() {
return this.isEmpty() ? -1 : this.queue[this.head];
}
Rear() {
return this.isEmpty() ? -1 : this.queue[this.tail];
}
isEmpty() {
return this.head === -1;
}
isFull() {
return (this.tail + 1) % this.size === this.head;
}
}
性能对比
- 数组队列:实现简单,但
dequeue操作需移动元素,适合数据量小的场景。 - 链表队列:
enqueue和dequeue均为O(1),适合频繁操作的场景。 - 循环队列:空间利用率高,适合固定大小的队列需求。






