{"record":{"id":"1fb516c724aade9a","repo":"krahets/hello-algo","slug":"error-1fb516","errorCode":null,"errorMessage":"栈为空","messagePattern":"栈为空","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"codes/python/chapter_stack_and_queue/linkedlist_stack.py","lineNumber":47,"sourceCode":"\n    def push(self, val: int):\n        \"\"\"入栈\"\"\"\n        node = ListNode(val)\n        node.next = self._peek\n        self._peek = node\n        self._size += 1\n\n    def pop(self) -> int:\n        \"\"\"出栈\"\"\"\n        num = self.peek()\n        self._peek = self._peek.next\n        self._size -= 1\n        return num\n\n    def peek(self) -> int:\n        \"\"\"访问栈顶元素\"\"\"\n        if self.is_empty():\n            raise IndexError(\"栈为空\")\n        return self._peek.val\n\n    def to_list(self) -> list[int]:\n        \"\"\"转化为列表用于打印\"\"\"\n        arr = []\n        node = self._peek\n        while node:\n            arr.append(node.val)\n            node = node.next\n        arr.reverse()\n        return arr\n\n\n\"\"\"Driver Code\"\"\"\nif __name__ == \"__main__\":\n    # 初始化栈\n    stack = LinkedListStack()\n","sourceCodeStart":29,"sourceCodeEnd":65,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/codes/python/chapter_stack_and_queue/linkedlist_stack.py#L29-L65","documentation":"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.","triggerScenarios":"Calling stack.peek() or stack.pop() when _peek is None (size 0).","commonSituations":"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.","solutions":["Guard with is_empty() before peek or pop.","Use while not stack.is_empty() as the drain condition.","When matching nested constructs, peek only when you expect a matching opener."],"exampleFix":"// before\ntop = stack.peek()  # raises on empty\n// after\ntop = stack.peek() if not stack.is_empty() else None","handlingStrategy":"validation","validationCode":"def safe_peek(stack):\n    return stack.peek() if not stack.is_empty() else None","typeGuard":"def stack_non_empty(stack) -> bool:\n    return not stack.is_empty()","tryCatchPattern":"try:\n    top = stack.peek()\nexcept IndexError:\n    top = None","preventionTips":["Check is_empty() before peek or pop.","Drive DFS-style drains with while not stack.is_empty().","Peek only when a matching element is expected."],"tags":["stack","linked-list","index-error","empty-structure","peek"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}