🚶 队列 Queue 可视化
队列是先进先出(FIFO)的数据结构,像排队买票,队尾进入队头离开
⬅ 队头 (front)
队尾 (rear) ➡
欢迎!体验队列的 enqueue 和 dequeue 操作
循环队列(环形缓冲)
循环队列用固定大小的数组实现,队头和队尾指针回绕(wrap around),避免数据搬移。 绿色框 = 队头,橙色框 = 队尾。
绿色=队头 橙色=队尾
JavaScript 实现
// 队列类实现(数组模拟) class Queue { constructor() { this.items = []; } // 入队 - O(1) enqueue(item) { this.items.push(item); } // 出队 - O(n) 用数组实现需要搬移 // 用链表实现为 O(1) dequeue() { if (this.isEmpty()) { throw new Error('Queue underflow'); } return this.items.shift(); } // 查看队头 - O(1) front() { return this.items[0]; } isEmpty() { return this.items.length === 0; } size() { return this.items.length; } } // 循环队列实现 class CircularQueue { constructor(capacity) { this.data = new Array(capacity).fill(null); this.front = 0; this.rear = 0; this.capacity = capacity; this.count = 0; } enqueue(item) { if (this.isFull()) throw new Error('Queue full'); this.data[this.rear] = item; this.rear = (this.rear + 1) % this.capacity; this.count++; } dequeue() { if (this.isEmpty()) throw new Error('Queue empty'); const item = this.data[this.front]; this.data[this.front] = null; this.front = (this.front + 1) % this.capacity; this.count--; return item; } isFull() { return this.count === this.capacity; } isEmpty() { return this.count === 0; } }
时间复杂度分析
| 操作 | 数组实现 | 链表实现 | 循环队列 |
|---|---|---|---|
| Enqueue 入队 | O(1) | O(1) | O(1) |
| Dequeue 出队 | O(n) | O(1) | O(1) |
| Front 查看队头 | O(1) | O(1) | O(1) |
| 空间利用率 | 中(搬移开销) | 中(指针开销) | 高(无搬移) |
实际应用场景
- 📨 消息队列:RabbitMQ、Kafka 等
- 🖨️ 打印任务:打印机任务队列
- 🔄 任务调度:操作系统进程调度
- 🌊 广度优先搜索:BFS 使用队列
- 🔄 滑动窗口:网络流量控制
- 📦 环形缓冲区:音频/视频流处理