krahets/hello-algo · error · IndexError

佇列為空

Error message

佇列為空

What it means

Raised by the peek method of the LinkedListQueue teaching class (a singly-linked-list FIFO queue) when is_empty? is true. It guards @front.val so you never dereference a nil front pointer. Note that pop calls peek internally, so dequeuing an empty queue also propagates this error.

Source

Thrown at zh-hant/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb:55

      @rear.next = node
      @rear = node
    end

    @size += 1
  end

  ### 出列 ###
  def pop
    num = peek
    # 刪除頭節點
    @front = @front.next
    @size -= 1
    num
  end

  ### 訪問佇列首元素 ###
  def peek
    raise IndexError, '佇列為空' if is_empty?

    @front.val
  end

  ### 將鏈結串列為 Array 並返回 ###
  def to_array
    queue = []
    temp = @front
    while temp
      queue << temp.val
      temp = temp.next
    end
    queue
  end
end

### Driver Code ###
if __FILE__ == $0

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check queue.is_empty? before calling peek or pop.
  2. Return nil when empty: queue.is_empty? ? nil : queue.peek.
  3. Use while !queue.is_empty? for safe draining.
  4. Track enqueue/dequeue counts to catch imbalances.

Example fix

# before
val = queue.peek  # raises on empty queue

# after
val = queue.is_empty? ? nil : queue.peek
Defensive patterns

Strategy: validation

Validate before calling

return nil if queue.is_empty?
queue.peek

Type guard

# Ruby: safe peek
def safe_peek(queue)
  queue.is_empty? ? nil : queue.peek
end

Try / catch

begin
  head = queue.peek
rescue IndexError
  head = nil
end

Prevention

When it happens

Trigger: Calling queue.peek or queue.pop on a newly constructed queue, calling them after all elements were dequeued, or draining past empty in a loop.

Common situations: Consumer reading faster than producer enqueues; peeking before any push; using a fixed-count drain loop instead of while !is_empty?.

Related errors


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