krahets/hello-algo · error · Error
栈为空
Error message
栈为空
What it means
Thrown by peek() on a singly-linked-list-backed stack when the internal #stackPeek is null (no nodes). peek() returns #stackPeek.val, which would throw a TypeError without the guard. pop() calls peek() first, so both surface the same error. The check is reference-based (!#stackPeek), equivalent to size === 0.
Source
Thrown at 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
- Guard: if (stack.size > 0) stack.peek(); (the class exposes size via a getter).
- Push a sentinel node for algorithms that assume a non-empty stack.
- Wrap in a helper returning null on empty rather than catching the throw.
- Track push/pop counts and assert balanced usage in tests.
Example fix
// before const t = stack.peek(); // throws if empty // after const t = stack.size > 0 ? stack.peek() : null;
Defensive patterns
Strategy: validation
Validate before calling
function safePeek(stack) {
return stack.size > 0 ? stack.peek() : null;
} Type guard
function stackNotEmpty(stack) {
return stack.size > 0;
} Try / catch
try {
const t = stack.peek();
} catch (e) {
if (e instanceof Error && e.message === '栈为空') { /* empty stack */ } else throw e;
} Prevention
- Guard peek()/pop() with stack.size > 0.
- Push a sentinel node for algorithms assuming non-empty.
- Wrap peek() in a null-returning helper.
- Track push/pop counts in tests.
When it happens
Trigger: Calling peek()/pop() on a freshly constructed stack; popping the last node then peeking again; DFS/backtracking unwind past the bottom; balanced-symbol checks on an empty input.
Common situations: Monotonic-stack top inspection before any push; expression evaluation with leading operators; recursive helpers that peek before pushing.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/9f5f1574a3e24491.
Report an issue: GitHub.