krahets/hello-algo · error · IndexError

队列已满

Error message

队列已满

What it means

IndexError '队列已满' (queue is full) raised by ArrayQueue.push. This queue is backed by a fixed-capacity circular array; when _size == capacity() there is no free slot, so the guard refuses the write rather than overwriting the front.

Source

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

        self._front: int = 0  # 队首指针,指向队首元素
        self._size: int = 0  # 队列长度

    def capacity(self) -> int:
        """获取队列的容量"""
        return len(self._nums)

    def size(self) -> int:
        """获取队列的长度"""
        return self._size

    def is_empty(self) -> bool:
        """判断队列是否为空"""
        return self._size == 0

    def push(self, num: int):
        """入队"""
        if self._size == self.capacity():
            raise IndexError("队列已满")
        # 计算队尾指针,指向队尾索引 + 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():

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check queue.size() < queue.capacity() before push, or wrap with a grow helper.
  2. Size the queue to the worst-case concurrent occupancy at construction.
  3. Consume (pop) before pushing in bounded-buffer scenarios, or use a dynamic queue for unbounded streams.

Example fix

// before
q.push(x)  # raises once fixed buffer fills
// after
if q.size() == q.capacity():
    q.pop()
q.push(x)
Defensive patterns

Strategy: validation

Validate before calling

def safe_push(q, num):
    if q.size() < q.capacity():
        q.push(num)
    else:
        raise OverflowError(f"queue full: {q.size()}/{q.capacity()}")

Type guard

def queue_has_room(q) -> bool:
    return q.size() < q.capacity()

Try / catch

try:
    q.push(x)
except IndexError:
    q.pop()  # evict oldest
    q.push(x)

Prevention

When it happens

Trigger: Calling queue.push(num) once _size reaches the array length. Also when capacity() is misreported or the caller pushes in a tight loop without consuming.

Common situations: Initializing ArrayQueue with a small capacity and feeding more items than it holds; producer/consumer where the producer outruns the consumer; forgetting that this implementation does not auto-grow unlike Python's collections.deque.

Related errors


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