krahets/hello-algo · error · Error

стек пуст

Error message

стек пуст

What it means

Thrown by pop() on a linked-list stack when this.stackPeek is null/undefined. The message ('стек пуст') guards the reassignment this.stackPeek = this.stackPeek.next. Note peek() is invoked first inside pop() and already throws on an empty stack, making this a redundant secondary guard.

Source

Thrown at ru/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. Check stack.isEmpty() before pop().
  2. Bound the pop count by stack.size() or use while (!stack.isEmpty()).
  3. Catch the error when an empty pop is recoverable.
  4. Verify push/pop balance in the surrounding algorithm.

Example fix

// before
const top = stack.pop(); // throws when stackPeek is null

// after
const top = stack.isEmpty() ? null : stack.pop();
Defensive patterns

Strategy: validation

Validate before calling

if (!stack.isEmpty()) {
    const top = stack.pop();
}

Try / catch

try {
    const top = stack.pop();
} catch (e) {
    if (e instanceof Error && e.message === 'стек пуст') {
        // empty stack; handle gracefully
    } else throw e;
}

Prevention

When it happens

Trigger: Calling pop() on a stack whose stackPeek pointer is null (nothing pushed, or all popped); unbalanced push/pop sequences in backtracking or expression evaluation.

Common situations: DFS/recursion-emulation that pops past the base; evaluator loops that pop operands without verifying availability; reusing a stack object after draining it.

Related errors


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