krahets/hello-algo · error · IndexError

スタックは空です

Error message

スタックは空です

What it means

Raised by LinkedListStack#peek (ja) on an empty stack. The class stores its top in `@peek`, and `pop` is `num = peek; @peek = @peek.next; @size -= 1` — so both `peek` and `pop` on an empty stack fail at this same raise (line 41). It guards against dereferencing nil @peek.

Source

Thrown at ja/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 `stack.is_empty?` before peek or pop.
  2. Drive pop loops with `while stack.size > 0` (or `until stack.is_empty?`).
  3. For optional behavior, wrap pop in a helper returning nil on empty instead of raising.

Example fix

// before
stack.pop  # raises 'スタックは空です' when empty

// after
val = stack.is_empty? ? nil : stack.pop
Defensive patterns

Strategy: validation

Validate before calling

val = stack.pop unless stack.is_empty?

Type guard

def stack_nonempty?(s) = !s.is_empty?

Try / catch

begin
  val = stack.pop  # also covers peek
rescue IndexError
  val = nil
end

Prevention

When it happens

Trigger: Calling `stack.peek` or `stack.pop` after the last element was popped, or on a never-pushed stack. Any pop loop that overshoots triggers it.

Common situations: Unwinding/popping all frames then popping once more; an algorithm that pops until empty and then peeks to verify; mismatched push/pop counts in a driver.

Related errors


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