js 实现队列
队列的基本概念
队列是一种先进先出(FIFO)的数据结构,支持在队尾插入元素(入队),在队头移除元素(出队)。JavaScript中可以通过数组或链表实现队列。
使用数组实现队列
数组的 push 和 shift 方法分别对应入队和出队操作:
class ArrayQueue {
constructor() {
this.items = [];
}
// 入队
enqueue(element) {
this.items.push(element);
}
// 出队
dequeue() {
if (this.isEmpty()) return "Queue is empty";
return this.items.shift();
}
// 查看队头元素
peek() {
if (this.isEmpty()) return "Queue is empty";
return this.items[0];
}
// 判断队列是否为空
isEmpty() {
return this.items.length === 0;
}
// 获取队列长度
size() {
return this.items.length;
}
// 清空队列
clear() {
this.items = [];
}
}
使用链表实现队列
链表实现可以避免数组 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 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 removedValue = this.head.value;
this.head = this.head.next;
this.length--;
if (this.length === 0) this.tail = null;
return removedValue;
}
// 查看队头元素
peek() {
return this.head?.value ?? null;
}
// 判断队列是否为空
isEmpty() {
return this.length === 0;
}
// 获取队列长度
size() {
return this.length;
}
}
性能对比
- 数组实现:
shift操作需要移动所有剩余元素,时间复杂度为 O(n)。 - 链表实现:入队和出队操作均为 O(1),适合频繁操作的场景。
实际应用示例
浏览器任务队列、消息队列等场景通常需要高效的队列实现。以下是一个简单的任务调度示例:
const taskQueue = new LinkedListQueue();
taskQueue.enqueue(() => console.log("Task 1"));
taskQueue.enqueue(() => console.log("Task 2"));
while (!taskQueue.isEmpty()) {
const task = taskQueue.dequeue();
task(); // 执行任务
}
扩展:循环队列
当队列容量固定时,循环队列可以复用空间:

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






