krahets/hello-algo · error · IndexError

堆疊為空

Error message

堆疊為空

What it means

Raised by the peek method of the LinkedListStack teaching class (a singly-linked-list LIFO stack) when is_empty? is true. It guards @peek.val (the top node pointer) so you never dereference nil. Note that pop calls peek internally, so popping an empty stack also propagates this error.

Source

Thrown at zh-hant/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. Check stack.is_empty? before calling peek or pop.
  2. Return nil when empty: stack.is_empty? ? nil : stack.peek.
  3. Use until stack.is_empty? for safe draining.
  4. Ensure at least one push precedes any peek or pop.

Example fix

# before
top = stack.peek  # raises on empty stack

# 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

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

Try / catch

begin
  top = stack.peek
rescue IndexError
  top = nil
end

Prevention

When it happens

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

Common situations: Peeking/popping before pushing; mismatched push/pop counts; assuming the stack has elements when it does not.

Related errors


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