krahets/hello-algo · error · IndexError

队列为空

Error message

队列为空

What it means

IndexError '队列为空' (queue is empty) raised by ArrayQueue.peek, and propagated by pop which calls peek first. Reading the front slot of an empty circular queue would return stale data, so the guard short-circuits.

Source

Thrown at codes/python/chapter_stack_and_queue/array_queue.py:51

        # 计算队尾指针,指向队尾索引 + 1
        # 通过取余操作实现 rear 越过数组尾部后回到头部
        rear: int = (self._front + self._size) % self.capacity()
        # 将 num 添加至队尾
        self._nums[rear] = num
        self._size += 1

    def pop(self) -> int:
        """出队"""
        num: int = self.peek()
        # 队首指针向后移动一位,若越过尾部,则返回到数组头部
        self._front = (self._front + 1) % self.capacity()
        self._size -= 1
        return num

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

    def to_list(self) -> list[int]:
        """返回列表用于打印"""
        res = [0] * self.size()
        j: int = self._front
        for i in range(self.size()):
            res[i] = self._nums[(j % self.capacity())]
            j += 1
        return res


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

    # 元素入队

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard with is_empty() before peek or pop.
  2. Drive consumption with while not q.is_empty(): item = q.pop().
  3. For optional access, expose a get-or-default wrapper.

Example fix

// before
front = q.peek()  # raises on 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 that pops after exhausting the queue; producer/consumer where the consumer starts before any push; off-by-one drain loop popping n+1 items.

Related errors


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