krahets/hello-algo · error · IndexError

堆疊為空

Error message

堆疊為空

What it means

Raised by the peek() method of a singly-linked-list-based stack (Traditional Chinese) when the internal _peek pointer is None. Since pop() calls peek() to read the top value before unlinking it (_peek = _peek.next), both operations fail on an empty stack. The guard prevents an AttributeError from dereferencing None.val.

Source

Thrown at zh-hant/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. Check stack.is_empty() before calling peek() or pop()
  2. Use while not stack.is_empty() as the draining loop condition
  3. Wrap in try/except IndexError for defensive stack operations

Example fix

# before
val = stack.peek()

# after
val = stack.peek() if not stack.is_empty() else None
Defensive patterns

Strategy: validation

Validate before calling

if not stack.is_empty():
    val = stack.peek()
else:
    val = None

Try / catch

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

Prevention

When it happens

Trigger: Calling peek() or pop() on a newly constructed LinkedListStack; calling pop() more times than push(); draining the stack completely and then accessing the top once more.

Common situations: Backtracking algorithms that pop past the initial state; undo stacks with nothing to undo; expression evaluators that attempt to read an operator from an empty operand stack.

Related errors


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