krahets/hello-algo · error
佇列為空
Error message
佇列為空
What it means
Unrecoverable Zig @panic from peek() on the singly-linked-list queue. Guard `if (self.size() == 0) @panic("佇列為空")` runs before `self.front.?.val`, preventing a null optional unwrap. Peeking an empty queue is defined as a logic error.
Source
Thrown at zh-hant/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
- Gate with `if (!q.isEmpty())` before peek().
- Loop `while (!q.isEmpty())` for consumption so no peek runs at size 0.
- Wrap with a ?T-returning helper for callers that legitimately face an empty queue.
Example fix
// before const head = q.peek(); // after const head = if (q.isEmpty()) null else q.peek();
Defensive patterns
Strategy: validation
Validate before calling
// call BEFORE peek() if (q.isEmpty()) return null; const head = q.peek();
Prevention
- Check isEmpty()/size() before peek().
- Consume with `while (!q.isEmpty())` so peek never runs at size 0.
- Build a ?T-returning wrapper if empty-peek is legitimate.
When it happens
Trigger: Call peek() on a LinkedListQueue with zero elements (never enqueued, or fully dequeued). Reached by helper code that peeks before the first push or after the final pop.
Common situations: BFS/level-order traversal peeking after draining the last node; polling a queue before the producer enqueues; UI/log code displaying the queue head without a size check.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/0d25ecb74824c846.
Report an issue: GitHub.