krahets/hello-algo · error · IndexError
队列为空
Error message
队列为空
What it means
Raised by `LinkedListQueue#peek` (linkedlist_queue.rb:55) when `is_empty?` is true. The method reads `@front.val`; on an empty queue `@front` is nil, so the guard prevents a NoMethodError. The `pop` method delegates to `peek`, so dequeueing an empty queue also triggers this.
Source
Thrown at 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__ == $0View on GitHub (pinned to 69932aed18)
Solutions
- Guard with `unless queue.is_empty?` before `peek` or `pop`.
- Drive the consumer with `while queue.size > 0`.
- Rescue IndexError if an empty peek is recoverable.
Example fix
# before head = queue.peek # after head = queue.is_empty? ? nil : queue.peek
Defensive patterns
Strategy: validation
Validate before calling
return nil if queue.is_empty? queue.peek
Type guard
def ll_queue_readable?(queue) queue.respond_to?(:is_empty?) && queue.respond_to?(:peek) && !queue.is_empty? end
Try / catch
begin queue.peek rescue IndexError nil end
Prevention
- Check is_empty? before peek or pop.
- In BFS, check frontier emptiness before peeking.
- Use while queue.size > 0 as the consumer loop bound.
When it happens
Trigger: Calling `queue.peek` or `queue.pop` when the linked list has no nodes (`@size == 0`). Occurs after consuming all elements or before the first enqueue.
Common situations: BFS frontier fully drained then peeked; consumer loop that pops past empty; queue shared across threads where one drains before the other peeks.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/8499fe9ec31a96b6.
Report an issue: GitHub.