krahets/hello-algo · error · IndexError
スタックが空です
Error message
スタックが空です
What it means
This IndexError (Japanese: 'スタックが空です' = 'stack is empty') is raised by LinkedListStack.peek() (linkedlist_stack.py:47) when _size == 0. peek() returns _peek.val; the guard avoids dereferencing _peek (None). pop() calls peek() first, so the same exception propagates through pop() on an empty stack. The linked-list stack is unbounded.
Source
Thrown at ja/codes/python/chapter_stack_and_queue/linkedlist_stack.py:47
def push(self, val: int):
"""プッシュ"""
node = ListNode(val)
node.next = self._peek
self._peek = node
self._size += 1
def pop(self) -> int:
"""ポップ"""
num = self.peek()
self._peek = self._peek.next
self._size -= 1
return num
def peek(self) -> int:
"""スタックトップの要素にアクセス"""
if self.is_empty():
raise IndexError("スタックが空です")
return self._peek.val
def to_list(self) -> list[int]:
"""表示用にリストへ変換"""
arr = []
node = self._peek
while node:
arr.append(node.val)
node = node.next
arr.reverse()
return arr
"""Driver Code"""
if __name__ == "__main__":
# スタックを初期化
stack = LinkedListStack()
View on GitHub (pinned to 69932aed18)
Solutions
- Guard with `if not stack.is_empty(): stack.peek()`.
- Drain with `while not stack.is_empty(): stack.pop()`.
- Track depth explicitly and never pop/peek at depth 0.
- Wrap pop in try/except IndexError if empty-pop is benign.
Example fix
// before top = stack.pop() # IndexError when empty // after top = stack.pop() if not stack.is_empty() else None
Defensive patterns
Strategy: validation
Validate before calling
if not stack.is_empty():
top = stack.peek()
# pop() calls peek() — guard pop() identically Type guard
def stack_has_top(stack: LinkedListStack) -> bool:
return not stack.is_empty() Try / catch
try:
top = stack.pop()
except IndexError:
top = None Prevention
- Guard peek() and pop() with is_empty() (pop delegates to peek).
- Drain with `while not stack.is_empty():`.
- Track push/pop balance in DFS/backtracking.
- The linked-list stack is unbounded, so only underflow can occur.
When it happens
Trigger: Calling peek() or pop() on a freshly constructed LinkedListStack (_peek is None). Calling pop() more times than push().
Common situations: Unbalanced push/pop in DFS/backtracking. Draining the stack then peeking/popping once more. Holding a stale assumption that the stack is non-empty after conditional pushes.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/1bc1cfd604ae14d3.
Report an issue: GitHub.