krahets/hello-algo · error · IndexError
双向队列为空
Error message
双向队列为空
What it means
Raised by `LinkedListDeque#pop` (linkedlist_deque.rb:70) when `is_empty?` is true. This is the internal pop shared by `pop_first` and `pop_last`; on an empty deque there is no node to detach, and dereferencing `@front.val` or `@rear.val` would fail. The guard prevents nil-dereference on the linked-list head/tail pointers.
Source
Thrown at codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb:70
node.prev = @rear
@rear = node # 更新尾节点
end
@size += 1 # 更新队列长度
end
### 队首入队 ###
def push_first(num)
push(num, true)
end
### 队尾入队 ###
def push_last(num)
push(num, false)
end
### 出队操作 ###
def pop(is_front)
raise IndexError, '双向队列为空' if is_empty?
# 队首出队操作
if is_front
val = @front.val # 暂存头节点值
# 删除头节点
fnext = @front.next
unless fnext.nil?
fnext.prev = nil
@front.next = nil
end
@front = fnext # 更新头节点
# 队尾出队操作
else
val = @rear.val # 暂存尾节点值
# 删除尾节点
rprev = @rear.prev
unless rprev.nil?
rprev.next = nilView on GitHub (pinned to 69932aed18)
Solutions
- Check `deque.is_empty?` before `pop_first` or `pop_last`.
- Loop with `until deque.is_empty?` when draining.
- Rescue IndexError if popping past empty is recoverable.
Example fix
# before val = deque.pop_first # after val = deque.is_empty? ? nil : deque.pop_first
Defensive patterns
Strategy: validation
Validate before calling
return nil if deque.is_empty? deque.pop_first
Type guard
def ll_deque_popable?(deque) deque.respond_to?(:is_empty?) && deque.respond_to?(:pop) && !deque.is_empty? end
Try / catch
begin deque.pop_first rescue IndexError nil end
Prevention
- Check is_empty? before pop_first or pop_last.
- Drain with until deque.is_empty? instead of a fixed count.
- Validate size before each two-ended consume step.
When it happens
Trigger: Calling `deque.pop_first` or `deque.pop_last` (both delegate to `pop`) on a deque with zero nodes. Occurs after removing all elements from both ends.
Common situations: Deque-based undo/redo fully consumed; deque used as a work-queue drained to empty; test calling pop on a new deque.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/1f7b79a9bdba78ca.
Report an issue: GitHub.