krahets/hello-algo · error · Error

栈为空

Error message

栈为空

What it means

Thrown by LinkedListStack.pop() ('栈为空') when stackPeek (the head node) is null. pop() first calls peek() (which also throws when stackPeek is null), then re-checks !this.stackPeek and throws a second time. Both guards protect against dereferencing a null head.

Source

Thrown at codes/typescript/chapter_stack_and_queue/linkedlist_stack.ts:39

    }

    /* 判断栈是否为空 */
    isEmpty(): boolean {
        return this.size === 0;
    }

    /* 入栈 */
    push(num: number): void {
        const node = new ListNode(num);
        node.next = this.stackPeek;
        this.stackPeek = node;
        this.stkSize++;
    }

    /* 出栈 */
    pop(): number {
        const num = this.peek();
        if (!this.stackPeek) throw new Error('栈为空');
        this.stackPeek = this.stackPeek.next;
        this.stkSize--;
        return num;
    }

    /* 访问栈顶元素 */
    peek(): number {
        if (!this.stackPeek) throw new Error('栈为空');
        return this.stackPeek.val;
    }

    /* 将链表转化为 Array 并返回 */
    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

  1. Guard with isEmpty()/size before pop: if (!stack.isEmpty()) stack.pop().
  2. Use while (!stack.isEmpty()) for draining.
  3. Audit sentinel handling so pops never exceed pushes.

Example fix

// before
const v = stack.pop(); // throws when empty
// after
if (!stack.isEmpty()) {
    const v = stack.pop();
}
Defensive patterns

Strategy: validation

Validate before calling

function safePop(stack) {
  return stack.isEmpty() ? undefined : stack.pop();
}

Type guard

null

Try / catch

null

Prevention

When it happens

Trigger: Calling pop() on an empty stack; an unbalanced push/pop sequence; a backtracking algorithm that pops one frame too many.

Common situations: Expression/AST evaluators using an explicit stack; DFS with an explicit stack that over-pops; calling pop right after construction.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/1c441ab0c1756aa4. Report an issue: GitHub.