krahets/hello-algo · error · Error
队列为空
Error message
队列为空
What it means
Thrown by LinkedListQueue.pop() ('队列为空') when front is null. pop() first calls peek() (which already throws on size 0), then redundantly re-checks !this.front and throws again. Both guards target the empty-queue case; the front-check is a defensive duplicate for the case where size and front disagree.
Source
Thrown at codes/typescript/chapter_stack_and_queue/linkedlist_queue.ts:49
push(num: number): void {
// 在尾节点后添加 num
const node = new ListNode(num);
// 如果队列为空,则令头、尾节点都指向该节点
if (!this.front) {
this.front = node;
this.rear = node;
// 如果队列不为空,则将该节点添加到尾节点后
} else {
this.rear!.next = node;
this.rear = node;
}
this.queSize++;
}
/* 出队 */
pop(): number {
const num = this.peek();
if (!this.front) throw new Error('队列为空');
// 删除头节点
this.front = this.front.next;
this.queSize--;
return num;
}
/* 访问队首元素 */
peek(): number {
if (this.size === 0) throw new Error('队列为空');
return this.front!.val;
}
/* 将链表转化为 Array 并返回 */
toArray(): number[] {
let node = this.front;
const res = new Array<number>(this.size);
for (let i = 0; i < res.length; i++) {
res[i] = node!.val;View on GitHub (pinned to 69932aed18)
Solutions
- Guard with size/isEmpty before pop: if (queue.size > 0) queue.pop().
- Use while (queue.size > 0) for draining.
- Track the enqueued count and never dequeue past it.
Example fix
// before
const v = queue.pop(); // throws when empty
// after
if (queue.size > 0) {
const v = queue.pop();
} Defensive patterns
Strategy: validation
Validate before calling
function safePop(queue) {
return queue.size > 0 ? queue.pop() : undefined;
} Type guard
null
Try / catch
null
Prevention
- Check queue.size > 0 (or front !== null) before pop.
- Use while (queue.size > 0) for draining.
- Track enqueue/dequeue counts.
When it happens
Trigger: Calling pop() on an empty queue (size 0 / front null); a consumer loop dequeuing more than was enqueued.
Common situations: Unbalanced enqueue/dequeue; a worker reading from a queue fed asynchronously that hits an empty window; calling pop right after construction.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/34480cc75beada90.
Report an issue: GitHub.