队列(Queue)结构
核心特性
先进先出(FIFO):操作队首(出队)和队尾(入队),先入队的元素先出队
核心操作:入队(enqueue)、出队(dequeue)、查看队首(front)、判断空(isEmpty)
代码实现(基于数组,简单版)
js
class Queue {
constructor() {
this.items = [];
}
// 入队(添加元素到队尾)
enqueue(item) {
this.items.push(item);
}
// 出队(删除并返回队首元素)
dequeue() {
if (this.isEmpty()) return null;
return this.items.shift(); // 注意:shift是O(n),大规模数据建议用链表优化
}
// 查看队首元素(不删除)
front() {
if (this.isEmpty()) return null;
return this.items[0];
}
// 判断队列是否为空
isEmpty() {
return this.items.length === 0;
}
// 获取队列大小
size() {
return this.items.length;
}
// 清空队列
clear() {
this.items = [];
}
}代码实现(基于链表,优化版)
出队 O (1)
js
class Queue {
constructor() {
this.head = null; // 队首
this.tail = null; // 队尾
this.size = 0;
}
enqueue(item) {
const node = { value: item, next: null };
if (this.isEmpty()) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
this.size++;
}
dequeue() {
if (this.isEmpty()) return null;
const value = this.head.value;
this.head = this.head.next;
if (!this.head) this.tail = null; // 队列为空时,重置tail
this.size--;
return value;
}
// 其他方法(front/isEmpty/size/clear)同上
}适用场景
异步任务队列:const taskQueue = new Queue()(如 Promise 队列,按顺序执行异步任务)
消息通知队列:用户收到的消息按顺序存储,依次展示
广度优先搜索(BFS):遍历树 / 图时,用队列存储待访问节点
