krahets/hello-algo · error · Error
Stack is empty
Error message
Stack is empty
What it means
Thrown by LinkedListStack.pop when stackPeek is null after peek. As with the queue case, this is a redundant defensive guard: pop calls peek() first, which already throws 'Stack is empty' when stackPeek is null. This branch is only reachable if stkSize and stackPeek are inconsistent. Treat it as the same empty-stack precondition as error 75.
Source
Thrown at en/codes/typescript/chapter_stack_and_queue/linkedlist_stack.ts:39
}
/* Check if the stack is empty */
isEmpty(): boolean {
return this.size === 0;
}
/* Push */
push(num: number): void {
const node = new ListNode(num);
node.next = this.stackPeek;
this.stackPeek = node;
this.stkSize++;
}
/* Pop */
pop(): number {
const num = this.peek();
if (!this.stackPeek) throw new Error('Stack is empty');
this.stackPeek = this.stackPeek.next;
this.stkSize--;
return num;
}
/* Return list for printing */
peek(): number {
if (!this.stackPeek) throw new Error('Stack is empty');
return this.stackPeek.val;
}
/* Convert linked list to Array and return */
toArray(): number[] {
let node = this.stackPeek;
const res = new Array<number>(this.size);
for (let i = res.length - 1; i >= 0; i--) {
res[i] = node!.val;
node = node!.next;View on GitHub (pinned to 69932aed18)
Solutions
- Check size() === 0 (or isEmpty if exposed) before pop.
- Drain with while (stack.size() > 0).
- Only mutate the stack through its public API.
Example fix
// before const v = stack.pop(); // throws if empty // after const v = stack.size() === 0 ? undefined : stack.pop();
Defensive patterns
Strategy: validation
Validate before calling
const v = stack.size() === 0 ? undefined : stack.pop();
Type guard
function hasElements(s) { return typeof s.size === 'function' && s.size() > 0; } Try / catch
try { return stack.pop(); }
catch (e) { if (!/Stack is empty/.test(e.message)) throw e; return undefined; } Prevention
- Check size() before pop.
- Drain with while (stack.size() > 0).
- Mutate internal pointers only via the public API to keep stkSize/stackPeek consistent.
When it happens
Trigger: Popping an empty stack (normally surfaced via peek first); corrupted state where stkSize > 0 but stackPeek is null.
Common situations: Calling pop without checking the stack depth; manual mutation of internal pointers; unbalanced push/pop in algorithm code.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/7176357ec0efc2d8.
Report an issue: GitHub.