krahets/hello-algo · error · IndexError

队列为空

Error message

队列为空

What it means

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.

Source

Thrown at codes/python/chapter_stack_and_queue/linkedlist_queue.py:56

            self._rear = node
        # 如果队列不为空,则将该节点添加到尾节点后
        else:
            self._rear.next = node
            self._rear = node
        self._size += 1

    def pop(self) -> int:
        """出队"""
        num = self.peek()
        # 删除头节点
        self._front = self._front.next
        self._size -= 1
        return num

    def peek(self) -> int:
        """访问队首元素"""
        if self.is_empty():
            raise IndexError("队列为空")
        return self._front.val

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


"""Driver Code"""
if __name__ == "__main__":
    # 初始化队列
    queue = LinkedListQueue()

    # 元素入队

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check is_empty() before peek or pop.
  2. Drive with while not q.is_empty(): node = q.pop().
  3. Return a sentinel for optional reads instead of peeking unconditionally.

Example fix

// before
front = q.peek()  # raises when empty
// after
front = q.peek() if not q.is_empty() else None
Defensive patterns

Strategy: validation

Validate before calling

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

Type guard

def queue_non_empty(q) -> bool:
    return not q.is_empty()

Try / catch

try:
    front = q.peek()
except IndexError:
    front = None

Prevention

When it happens

Trigger: Calling queue.peek() or queue.pop() when _size == 0.

Common situations: 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.

Related errors


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