krahets/hello-algo · error
队列为空
Error message
队列为空
What it means
This panic is raised by peek() in a singly-linked-list queue (Chinese localization). It fires when reading the front element of a queue whose size is zero. The guard is an explicit size()==0 check followed by @panic, because Zig has no null-return convention and silently returning a zero-value T would hide a caller bug. @panic aborts the program and cannot be caught with try/catch.
Source
Thrown at codes/zig/chapter_stack_and_queue/linkedlist_queue.zig:48
// 析构函数(释放内存)
pub fn deinit(self: *Self) void {
if (self.mem_arena == null) return;
self.mem_arena.?.deinit();
}
// 获取队列的长度
pub fn size(self: *Self) usize {
return self.que_size;
}
// 判断队列是否为空
pub fn isEmpty(self: *Self) bool {
return self.size() == 0;
}
// 访问队首元素
pub fn peek(self: *Self) T {
if (self.size() == 0) @panic("队列为空");
return self.front.?.val;
}
// 入队
pub fn push(self: *Self, num: T) !void {
// 在尾节点后添加 num
var node = try self.mem_allocator.create(inc.ListNode(T));
node.init(num);
// 如果队列为空,则令头、尾节点都指向该节点
if (self.front == null) {
self.front = node;
self.rear = node;
// 如果队列不为空,则将该节点添加到尾节点后
} else {
self.rear.?.next = node;
self.rear = node;
}
self.que_size += 1;View on GitHub (pinned to 69932aed18)
Solutions
- Guard with queue.isEmpty() before every peek() call.
- In a consume loop, use while (!queue.isEmpty()) and call peek/pop only inside the loop body.
- Cache queue.size() locally and branch on it before reading the front.
- Replace peek() with a custom accessor that returns ?T if recoverable semantics are required.
Example fix
// before
var head = queue.peek(); // @panics when empty
// after
while (!queue.isEmpty()) {
var head = queue.peek();
_ = queue.pop();
} Defensive patterns
Strategy: validation
Validate before calling
// Validate non-empty before reading the front
if (!queue.isEmpty()) {
var head = queue.peek();
} Prevention
- Use while (!queue.isEmpty()) as the consume-loop condition.
- Do not assume peek() returns null/zero on empty — it aborts.
- Cache queue.size() locally if you read the front conditionally.
When it happens
Trigger: Calling queue.peek() on a newly-constructed empty queue, or after pop() has drained all previously-pushed elements.
Common situations: BFS/level-order traversal reading the queue front after the last node is dequeued; porting Java/Python queue code that expects a catchable EmptyQueueException; forgetting that a single-element queue becomes empty after one pop.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/e4d5ad026004fb41.
Report an issue: GitHub.