{"record":{"id":"d0b042392982d4ef","repo":"krahets/hello-algo","slug":"error-d0b042","errorCode":null,"errorMessage":"队列为空","messagePattern":"队列为空","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"codes/python/chapter_stack_and_queue/linkedlist_queue.py","lineNumber":56,"sourceCode":"            self._rear = node\n        # 如果队列不为空，则将该节点添加到尾节点后\n        else:\n            self._rear.next = node\n            self._rear = node\n        self._size += 1\n\n    def pop(self) -> int:\n        \"\"\"出队\"\"\"\n        num = self.peek()\n        # 删除头节点\n        self._front = self._front.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._front.val\n\n    def to_list(self) -> list[int]:\n        \"\"\"转化为列表用于打印\"\"\"\n        queue = []\n        temp = self._front\n        while temp:\n            queue.append(temp.val)\n            temp = temp.next\n        return queue\n\n\n\"\"\"Driver Code\"\"\"\nif __name__ == \"__main__\":\n    # 初始化队列\n    queue = LinkedListQueue()\n\n    # 元素入队","sourceCodeStart":38,"sourceCodeEnd":74,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/codes/python/chapter_stack_and_queue/linkedlist_queue.py#L38-L74","documentation":"IndexError '队列为空' (queue is empty) raised by LinkedListQueue.peek, and inherited by pop which calls peek first. Reading _front.val on an empty queue would dereference None, so the guard intercepts.","triggerScenarios":"Calling queue.peek() or queue.pop() when _size == 0.","commonSituations":"BFS where the frontier is popped after exhaustion; level-order traversal whose termination check is off by one; consumer that starts before the producer's first push.","solutions":["Check is_empty() before peek or pop.","Drive with while not q.is_empty(): node = q.pop().","Return a sentinel for optional reads instead of peeking unconditionally."],"exampleFix":"// before\nfront = q.peek()  # raises when empty\n// after\nfront = q.peek() if not q.is_empty() else None","handlingStrategy":"validation","validationCode":"def safe_peek(q):\n    return q.peek() if not q.is_empty() else None","typeGuard":"def queue_non_empty(q) -> bool:\n    return not q.is_empty()","tryCatchPattern":"try:\n    front = q.peek()\nexcept IndexError:\n    front = None","preventionTips":["Guard peek and pop with is_empty().","Use while not q.is_empty() in BFS consumers.","Start consumers only after the first push."],"tags":["queue","linked-list","index-error","empty-structure","peek"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}