krahets/hello-algo · error · Error

队列为空

Error message

队列为空

What it means

Thrown by peek() on a singly-linked-list-backed queue when size === 0. peek() returns this.#front.val; on an empty queue #front is null/undefined so .val would crash — the guard returns a clean error instead. pop() calls peek() internally, so both throw identically.

Source

Thrown at 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 isEmpty if exposed) before peek/pop.
  2. Drain with while (queue.size > 0) queue.pop();.
  3. Track enqueue count and never exceed it on dequeue.
  4. Reset/reconstruct the queue rather than reusing a drained one if its internal pointers are suspect.

Example fix

// before
const head = q.peek(); // throws if empty
// after
const head = q.size > 0 ? q.peek() : null;
Defensive patterns

Strategy: validation

Validate before calling

function safePeek(q) {
  return q.size > 0 ? q.peek() : null;
}

Type guard

function queueNotEmpty(q) {
  return q.size > 0;
}

Try / catch

try {
  const head = q.peek();
} catch (e) {
  if (e instanceof Error && e.message === '队列为空') { /* empty queue */ } else throw e;
}

Prevention

When it happens

Trigger: Calling peek()/pop() on a freshly constructed queue; dequeuing more than was enqueued; drain loop without an emptiness check.

Common situations: BFS frontier; task queue drained ahead of production; off-by-one in producer/consumer counts; reusing a queue object after it was drained without re-initializing front.

Related errors


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