{"record":{"id":"23305a70fbd311ac","repo":"krahets/hello-algo","slug":"error-23305a","errorCode":null,"errorMessage":"栈为空","messagePattern":"栈为空","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"codes/ruby/chapter_stack_and_queue/linkedlist_stack.rb","lineNumber":41,"sourceCode":"  ### 入栈 ###\n  def push(val)\n    node = ListNode.new(val)\n    node.next = @peek\n    @peek = node\n    @size += 1\n  end\n\n  ### 出栈 ###\n  def pop\n    num = peek\n    @peek = @peek.next\n    @size -= 1\n    num\n  end\n\n  ### 访问栈顶元素 ###\n  def peek\n    raise IndexError, '栈为空' if is_empty?\n\n    @peek.val\n  end\n\n  ### 将链表转化为 Array 并反回 ###\n  def to_array\n    arr = []\n    node = @peek\n    while node\n      arr << node.val\n      node = node.next\n    end\n    arr.reverse\n  end\nend\n\n### Driver Code ###\nif __FILE__ == $0","sourceCodeStart":23,"sourceCodeEnd":59,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/codes/ruby/chapter_stack_and_queue/linkedlist_stack.rb#L23-L59","documentation":"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.","triggerScenarios":"Calling `stack.peek` or `stack.pop` when the linked list has no nodes. Occurs after popping all items or on a new stack.","commonSituations":"Unbalanced push/pop in expression evaluation; backtracking that over-pops; test calling pop/peek before any push.","solutions":["Guard with `unless stack.is_empty?` before `peek` or `pop`.","Track push/pop balance externally.","Rescue IndexError if an empty top-read is recoverable."],"exampleFix":"# before\ntop = stack.peek\n\n# after\ntop = stack.is_empty? ? nil : stack.peek","handlingStrategy":"validation","validationCode":"return nil if stack.is_empty?\nstack.peek","typeGuard":"def ll_stack_peekable?(stack)\n  stack.respond_to?(:is_empty?) && stack.respond_to?(:peek) && !stack.is_empty?\nend","tryCatchPattern":"begin\n  stack.peek\nrescue IndexError\n  nil\nend","preventionTips":["Check is_empty? before peek or pop.","Maintain a balanced push/pop invariant in the caller.","In expression evaluation, verify stack depth before reading the top."],"tags":["ruby","stack","linked-list","precondition","empty-state"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}