krahets/hello-algo · error

栈为空

Error message

栈为空

What it means

This panic is raised by peek() in a singly-linked-list stack (Chinese localization). It fires when reading the top element of a stack whose stk_size is zero. The implementation deliberately aborts rather than returning a sentinel, since an empty-stack read is a programmer error. @panic is non-recoverable in Zig.

Source

Thrown at codes/zig/chapter_stack_and_queue/linkedlist_stack.zig:46

        // 析构函数(释放内存)
        pub fn deinit(self: *Self) void {
            if (self.mem_arena == null) return;
            self.mem_arena.?.deinit();
        }

        // 获取栈的长度
        pub fn size(self: *Self) usize {
            return self.stk_size;
        }

        // 判断栈是否为空
        pub fn isEmpty(self: *Self) bool {
            return self.size() == 0;
        }

        // 访问栈顶元素
        pub fn peek(self: *Self) T {
            if (self.size() == 0) @panic("栈为空");
            return self.stack_top.?.val;
        }  

        // 入栈
        pub fn push(self: *Self, num: T) !void {
            var node = try self.mem_allocator.create(inc.ListNode(T));
            node.init(num);
            node.next = self.stack_top;
            self.stack_top = node;
            self.stk_size += 1;
        } 

        // 出栈
        pub fn pop(self: *Self) T {
            var num = self.peek();
            self.stack_top = self.stack_top.?.next;
            self.stk_size -= 1;
            return num;

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check stack.isEmpty() before calling peek().
  2. Use a guarded loop: while (!stack.isEmpty()) { ... } and only peek/pop inside.
  3. Verify stk_size via stack.size() > 0 before any top access.
  4. Wrap the stack in a helper that returns ?T for recoverable use.

Example fix

// before
var top = stack.peek(); // @panics when empty

// after
if (stack.isEmpty()) return;
var top = stack.peek();
Defensive patterns

Strategy: validation

Validate before calling

// Validate non-empty before reading the top
if (!stack.isEmpty()) {
    var top = stack.peek();
}

Prevention

When it happens

Trigger: Calling stack.peek() on a fresh stack, or after pop() has removed the last element.

Common situations: Expression-evaluation / parenthesis-matching that peeks the operator stack after it is drained; DFS recursion-elimination where the stack is checked at the wrong point; porting code that relied on catching an EmptyStackException.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/81fdb04913b4d058. Report an issue: GitHub.