krahets/hello-algo · error · Error

佇列為空

Error message

佇列為空

What it means

Thrown by LinkedListQueue.peek() (message: '佇列為空' = 'queue is empty') when size === 0. peek() dereferences front.val; without the guard it would throw a TypeError on null. pop() delegates to peek(), so dequeueing an empty queue surfaces this error.

Source

Thrown at zh-hant/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js:57

        } else {
            this.#rear.next = node;
            this.#rear = node;
        }
        this.#queSize++;
    }

    /* 出列 */
    pop() {
        const num = this.peek();
        // 刪除頭節點
        this.#front = this.#front.next;
        this.#queSize--;
        return num;
    }

    /* 訪問佇列首元素 */
    peek() {
        if (this.size === 0) throw new Error('佇列為空');
        return this.#front.val;
    }

    /* 將鏈結串列轉化為 Array 並返回 */
    toArray() {
        let node = this.#front;
        const res = new Array(this.size);
        for (let i = 0; i < res.length; i++) {
            res[i] = node.val;
            node = node.next;
        }
        return res;
    }
}

/* Driver Code */
/* 初始化佇列 */
const queue = new LinkedListQueue();

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check queue.size > 0 (or a custom isEmpty) before pop() or peek().
  2. Guard drain loops with while (queue.size > 0).
  3. Initialize the queue and enqueue at least one element before peeking.

Example fix

// before
const val = queue.pop(); // throws '佇列為空' (pop calls peek)

// after
while (queue.size > 0) {
    const val = queue.pop();
}
Defensive patterns

Strategy: validation

Validate before calling

// peek() and pop() (which calls peek) both throw on empty
if (queue.size > 0) {
    const val = queue.pop();
}

Try / catch

try {
    const val = queue.pop();
} catch (e) {
    if (e.message === '佇列為空') {
        // queue is empty — handle underflow
    } else throw e;
}

Prevention

When it happens

Trigger: Calling pop() or peek() on a queue with no nodes, or dequeuing more items than enqueued.

Common situations: BFS exhaustion; producer/consumer mismatch; calling pop before any enqueue.

Related errors


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