krahets/hello-algo · error · Error

スタックが空です

Error message

スタックが空です

What it means

Thrown by pop() on the linked-list-backed stack when `this.stackPeek` is null. Defensive duplicate: pop() calls peek() first (which throws the same message when stackPeek is null), so reaching this line implies an invariant violation where stkSize is non-zero but stackPeek is null.

Source

Thrown at ja/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 pop() with `if (stack.size > 0)` — this routes through peek and avoids the throw under normal use.
  2. Keep stackPeek and stkSize consistent; do not mutate them externally.
  3. In subclasses, preserve stackPeek===null ⇔ stkSize===0.

Example fix

// before
const v = stack.pop();

// after
const v = stack.size > 0 ? stack.pop() : undefined;
Defensive patterns

Strategy: validation

Validate before calling

// Guard linked-list stack pop (peek throws first with the same message).
if (stack.size > 0) {
  const v = stack.pop();
}

Type guard

function linkedStackCanPop(stack) {
  return stack.size > 0;
}

Try / catch

try {
  const v = stack.pop();
} catch (e) {
  if (e instanceof Error && e.message === 'スタックが空です') {
    // empty (or invariant violated)
  } else throw e;
}

Prevention

When it happens

Trigger: Calling pop() on an empty stack (peek throws first with the same message); externally mutating stackPeek/stkSize so they disagree; subclassing and breaking the head⇔size invariant.

Common situations: Normal empty-stack pop is caught by peek's check; this pop-level throw signals internal-state corruption. Reaching it usually means direct field manipulation outside the class API.

Related errors


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