krahets/hello-algo · error · Error
堆疊為空
Error message
堆疊為空
What it means
Thrown by LinkedListStack.peek() (message: '堆疊為空' = 'stack is empty') when stackPeek is null. peek() reads stackPeek.val; without the guard a TypeError would occur. pop() delegates to peek(), so popping an empty stack surfaces this error.
Source
Thrown at zh-hant/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.size > 0 (or !stack.isEmpty()) before pop() or peek().
- Ensure push/pop are balanced in expression evaluation and DFS.
- Return null instead of calling peek() when the stack is empty.
Example fix
// before
const val = stack.pop(); // throws '堆疊為空' (pop calls peek)
// after
if (stack.size > 0) {
const val = stack.pop();
} Defensive patterns
Strategy: validation
Validate before calling
// peek() and pop() (which calls peek) both throw on empty
if (stack.size > 0) {
const val = stack.pop();
} Try / catch
try {
const val = stack.pop();
} catch (e) {
if (e.message === '堆疊為空') {
// stack is empty — handle underflow
} else throw e;
} Prevention
- Check stack.size > 0 before pop() or peek().
- Ensure push/pop are balanced in DFS and expression evaluation.
- Return null instead of peek() when the stack is empty.
When it happens
Trigger: Calling pop() or peek() when no nodes have been pushed, or after all nodes were popped.
Common situations: Unbalanced push/pop in algorithm code; backtracking past the sentinel; DFS that pops the last element then peeks.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/465ed327340994db.
Report an issue: GitHub.