krahets/hello-algo · error · Error
スタックが空
Error message
スタックが空
What it means
Thrown by the linked-list stack's peek when the stack pointer (#stackPeek) is null/undefined, i.e. the stack is empty. peek reads #stackPeek.val; the guard converts what would be a TypeError (reading .val of null) into a clear domain error. pop() calls peek() first, so popping an empty stack surfaces the same message.
Source
Thrown at ja/codes/javascript/chapter_stack_and_queue/linkedlist_stack.js:46
/* プッシュ */
push(num) {
const node = new ListNode(num);
node.next = this.#stackPeek;
this.#stackPeek = node;
this.#stkSize++;
}
/* ポップ */
pop() {
const num = this.peek();
this.#stackPeek = this.#stackPeek.next;
this.#stkSize--;
return num;
}
/* スタックトップの要素にアクセス */
peek() {
if (!this.#stackPeek) throw new Error('スタックが空');
return this.#stackPeek.val;
}
/* 連結リストを Array に変換して返す */
toArray() {
let node = this.#stackPeek;
const res = new Array(this.size);
for (let i = res.length - 1; i >= 0; i--) {
res[i] = node.val;
node = node.next;
}
return res;
}
}
/* Driver Code */
/* スタックを初期化 */
const stack = new LinkedListStack();View on GitHub (pinned to 69932aed18)
Solutions
- Check !stack.isEmpty() (or #stackPeek presence via an exposed method) before peek()/pop().
- Use while (!stack.isEmpty()) for drain loops.
- Return a sentinel when empty instead of throwing.
- Keep push/pop counts balanced.
Example fix
// before const top = stack.peek(); // throws if empty // after const top = stack.isEmpty() ? null : stack.peek();
Defensive patterns
Strategy: validation
Validate before calling
function safePeek(stack) {
return stack.isEmpty() ? null : stack.peek();
} Type guard
const isNonEmpty = (s) => typeof s.isEmpty === 'function' && !s.isEmpty();
Try / catch
try {
return stack.peek();
} catch (e) {
if (e instanceof Error && e.message === 'スタックが空') return null;
throw e;
} Prevention
- Check isEmpty() before peek()/pop().
- Keep push/pop counts balanced.
- Return a sentinel for empty peeks.
When it happens
Trigger: Calling peek() or pop() on an empty stack (no pushes, or fully popped); calling after #stackPeek was reset to null.
Common situations: Unbalanced push/pop in algorithms; peeking before the first push; recursion-simulation stacks that drain.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/0c44a16d34f8ba4b.
Report an issue: GitHub.