krahets/hello-algo · error · IndexError
стек пуст
Error message
стек пуст
What it means
Raised by LinkedListStack#peek (ru) on an empty stack. `pop` is implemented as `num = peek; @peek = @peek.next; @size -= 1`, so this same raise fires for both `peek` and `pop` when empty — the failure originates at the peek call inside pop. It guards against nil @peek.
Source
Thrown at ru/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__ == $0View on GitHub (pinned to 69932aed18)
Solutions
- Guard with `stack.is_empty?` before peek or pop.
- Drive pop loops with `while stack.size > 0`.
- Wrap pop in a helper returning nil on empty for optional semantics.
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
- pop routes through peek — guard covers both.
- Drive pop loops with `while stack.size > 0`.
- Linked-list stack has no capacity limit — only the empty precondition raises.
When it happens
Trigger: Calling `stack.peek` or `stack.pop` on an empty LinkedListStack (never pushed, or fully popped). Any pop loop that overshoots triggers it.
Common situations: Unwinding then over-popping; mismatched push/pop counts; an algorithm that pops-to-empty then peeks to verify.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/f7113c134dba7338.
Report an issue: GitHub.