krahets/hello-algo · error · Error
стек пуст
Error message
стек пуст
What it means
Thrown by LinkedListStack.peek (JS) with message 'стек пуст' when #stackPeek is null (no nodes). pop() calls peek() first, so the throw also surfaces from pop() on an empty stack.
Source
Thrown at ru/codes/javascript/chapter_stack_and_queue/linkedlist_stack.js:46
/* Поместить в стек */
push(num) {
const node = new ListNode(num);
node.next = this.#stackPeek;
this.#stackPeek = node;
this.#stkSize++;
}
/* Извлечь из стека */
pop() {
const num = this.peek();
this.#stackPeek = this.#stackPeek.next;
this.#stkSize--;
return num;
}
/* Доступ к верхнему элементу стека */
peek() {
if (!this.#stackPeek) throw new Error('стек пуст');
return this.#stackPeek.val;
}
/* Преобразовать связный список в Array и вернуть */
toArray() {
let node = this.#stackPeek;
const res = new Array(this.size);
for (let i = res.length - 1; i >= 0; i--) {
res[i] = node.val;
node = node.next;
}
return res;
}
}
/* Driver Code */
/* Инициализация стека */
const stack = new LinkedListStack();View on GitHub (pinned to 69932aed18)
Solutions
- Guard on isEmpty()/size before peek or pop.
- Treat empty-on-pop as a domain-level 'unbalanced' signal rather than a crash.
- Maintain an explicit size invariant alongside the head pointer.
Example fix
// before const v = stack.peek(); // throws when empty // after const v = stack.isEmpty() ? null : stack.peek();
Defensive patterns
Strategy: validation
Validate before calling
const v = stack.isEmpty() ? null : stack.pop();
Try / catch
try { stack.peek(); } catch (e) { if (e.message !== 'стек пуст') throw e; } Prevention
- Guard peek/pop with isEmpty() since the head pointer is null when empty.
- Treat empty-on-pop in DFS simulation as a domain signal, not a crash.
- Keep #stkSize and #stackPeek in sync if you subclass.
When it happens
Trigger: Calling peek() or pop() when #stackPeek === null, i.e., the linked list is empty (#stkSize === 0).
Common situations: Over-popping a linked-list-backed stack; DFS/recursion simulation that pops more than it pushes; bracket matching closing with an empty stack.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/37f8462b2542c6e5.
Report an issue: GitHub.