krahets/hello-algo · error · IndexError

栈为空

Error message

栈为空

What it means

Raised by `LinkedListStack#peek` (linkedlist_stack.rb:41) when `is_empty?` is true. The method reads `@peek.val` (the stack uses `@peek` as the head/top pointer); on an empty stack `@peek` is nil, so the guard prevents nil-dereference. The `pop` method delegates to `peek`, so popping an empty stack also triggers this.

Source

Thrown at codes/ruby/chapter_stack_and_queue/linkedlist_stack.rb:41

  ### 入栈 ###
  def push(val)
    node = ListNode.new(val)
    node.next = @peek
    @peek = node
    @size += 1
  end

  ### 出栈 ###
  def pop
    num = peek
    @peek = @peek.next
    @size -= 1
    num
  end

  ### 访问栈顶元素 ###
  def peek
    raise IndexError, '栈为空' if is_empty?

    @peek.val
  end

  ### 将链表转化为 Array 并反回 ###
  def to_array
    arr = []
    node = @peek
    while node
      arr << node.val
      node = node.next
    end
    arr.reverse
  end
end

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

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard with `unless stack.is_empty?` before `peek` or `pop`.
  2. Track push/pop balance externally.
  3. Rescue IndexError if an empty top-read is recoverable.

Example fix

# before
top = stack.peek

# after
top = stack.is_empty? ? nil : stack.peek
Defensive patterns

Strategy: validation

Validate before calling

return nil if stack.is_empty?
stack.peek

Type guard

def ll_stack_peekable?(stack)
  stack.respond_to?(:is_empty?) && stack.respond_to?(:peek) && !stack.is_empty?
end

Try / catch

begin
  stack.peek
rescue IndexError
  nil
end

Prevention

When it happens

Trigger: Calling `stack.peek` or `stack.pop` when the linked list has no nodes. Occurs after popping all items or on a new stack.

Common situations: Unbalanced push/pop in expression evaluation; backtracking that over-pops; test calling pop/peek before any push.

Related errors


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