Queue
A queue is FIFO: the first item that enters is the first item that leaves.
先从这个心智模型开始
A queue is FIFO: the first item that enters is the first item that leaves.
它如何工作,不堆砌不必要的术语
Values enter at the rear and leave from the front.
Queues are ideal when work must be processed in arrival order.
把算法读成一连串决策
Identify the invariant that must always remain true.
Follow the read/update path through the structure.
After a mutation, restore the invariant before returning.
enqueue A, B, C; dequeue returns A first.
class Queue {
#items = [];
#head = 0;
enqueue(value) { this.#items.push(value); }
dequeue() {
if (this.#head >= this.#items.length) return undefined;
return this.#items[this.#head++];
}
}不要死记语法。跟踪每一行中发生变化的状态,并把它与上面描述的不变量联系起来。
enqueue/dequeue O(1)
Do not quote this complexity mechanically. Ask which operation or input dimension it describes, then derive the cost from the loops, recursion depth, data-structure operations and any preprocessing assumptions.
适用场景
- BFS
- Job scheduling
- Request buffering
通常哪里会出错
- Memorizing complexity without understanding representation.
- Ignoring worst-case shape or resizing/rebalancing costs.
专业回答结构
Mention FIFO and explain that a production JS queue should avoid repeated Array.shift() for large workloads; use a head index or deque implementation.
What problem does Queue solve?
A queue is FIFO: the first item that enters is the first item that leaves.
关于复杂度应该提到什么?
Its typical cost here is enqueue/dequeue O(1), but a complete answer should connect that cost to the representation, input constraints and the dominant operations.
最常见的错误是什么?
Memorizing complexity without understanding representation.