krahets/hello-algo · error · IndexError

佇列為空

Error message

佇列為空

What it means

Raised by the peek() method of a singly-linked-list-based queue when the internal _front pointer is None (i.e., _size == 0). Since pop() calls peek() to read the front value before advancing _front = _front.next, both operations fail on an empty queue. Without the guard, pop() would dereference None.next and crash with AttributeError.

Source

Thrown at zh-hant/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 queue.is_empty() before calling peek() or pop()
  2. Use while not queue.is_empty() as the draining loop condition
  3. Wrap in try/except IndexError for defensive queue operations

Example fix

# before
val = queue.pop()

# after
if not queue.is_empty():
    val = queue.pop()
else:
    val = None
Defensive patterns

Strategy: validation

Validate before calling

if not queue.is_empty():
    val = queue.pop()
else:
    val = None

Try / catch

try:
    val = queue.pop()
except IndexError:
    val = None

Prevention

When it happens

Trigger: Calling peek() or pop() on a freshly constructed LinkedListQueue; draining all elements and then calling pop() once more; a consumer processing items faster than the producer enqueues them.

Common situations: BFS traversal that processes all nodes and then attempts one more dequeue; task queues that are momentarily empty between producer batches; testing with empty input collections.

Related errors


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