krahets/hello-algo · error · IndexError

栈为空

Error message

栈为空

What it means

IndexError '栈为空' (stack is empty) raised by LinkedListStack.peek, and inherited by pop which calls peek first. Reading _peek.val when the stack is empty would dereference a None top pointer, so the guard produces a clear message.

Source

Thrown at codes/python/chapter_stack_and_queue/linkedlist_stack.py:47

    def push(self, val: int):
        """入栈"""
        node = ListNode(val)
        node.next = self._peek
        self._peek = node
        self._size += 1

    def pop(self) -> int:
        """出栈"""
        num = self.peek()
        self._peek = self._peek.next
        self._size -= 1
        return num

    def peek(self) -> int:
        """访问栈顶元素"""
        if self.is_empty():
            raise IndexError("栈为空")
        return self._peek.val

    def to_list(self) -> list[int]:
        """转化为列表用于打印"""
        arr = []
        node = self._peek
        while node:
            arr.append(node.val)
            node = node.next
        arr.reverse()
        return arr


"""Driver Code"""
if __name__ == "__main__":
    # 初始化栈
    stack = LinkedListStack()

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard with is_empty() before peek or pop.
  2. Use while not stack.is_empty() as the drain condition.
  3. When matching nested constructs, peek only when you expect a matching opener.

Example fix

// before
top = stack.peek()  # raises on empty
// after
top = stack.peek() if not stack.is_empty() else None
Defensive patterns

Strategy: validation

Validate before calling

def safe_peek(stack):
    return stack.peek() if not stack.is_empty() else None

Type guard

def stack_non_empty(stack) -> bool:
    return not stack.is_empty()

Try / catch

try:
    top = stack.peek()
except IndexError:
    top = None

Prevention

When it happens

Trigger: Calling stack.peek() or stack.pop() when _peek is None (size 0).

Common situations: Expression evaluation that peeks for an operator before any operand is pushed; DFS simulation with an incorrect loop bound; calling pop after the matching push was already consumed.

Related errors


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