TheAlgorithms/Java · error · NoSuchElementException
Empty stack. Nothing to peek
Error message
Empty stack. Nothing to peek
What it means
Thrown by StackOfLinkedList.peek() when the stack holds no elements (size==0). peek() reads head.data, which would NPE on an empty stack. The NoSuchElementException enforces that a top element must exist before it is inspected.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java:94
throw new NoSuchElementException("Empty stack. Nothing to pop");
}
Node destroy = head;
head = head.next;
int retValue = destroy.data;
destroy = null; // Help garbage collection
size--;
return retValue;
}
/**
* Returns the top element of the stack without removing it.
*
* @return the element at the top of the stack
* @throws NoSuchElementException if the stack is empty
*/
public int peek() {
if (size == 0) {
throw new NoSuchElementException("Empty stack. Nothing to peek");
}
return head.data;
}
@Override
public String toString() {
Node cur = head;
StringBuilder builder = new StringBuilder();
while (cur != null) {
builder.append(cur.data).append("->");
cur = cur.next;
}
return builder.replace(builder.length() - 2, builder.length(), "").toString(); // Remove the last "->"
}
/**
* Checks if the stack is empty.
*View on GitHub (pinned to fdfb9a395b)
Solutions
- Check size==0 before calling peek().
- Seed the stack with a sentinel so it is never empty during the peek window.
- Terminate loops on the empty condition rather than an external counter.
- Catch NoSuchElementException if empty-peek is a legitimate branch.
Example fix
// before int top = stack.peek(); // after int top = (stack.size() == 0) ? defaultValue : stack.peek();
Defensive patterns
Strategy: validation
Validate before calling
int top = (stack.size() == 0) ? defaultValue : stack.peek();
Prevention
- Guard peek() with a size check.
- Seed a sentinel when the algorithm must always peek.
- Terminate loops on the empty condition.
When it happens
Trigger: Calling peek() on a fresh StackOfLinkedList. Calling peek() after draining the stack. Inspecting the top in an algorithm before any push has occurred.
Common situations: Parsing or matching algorithms that peek before seeding a sentinel. Stateful processors with an uninitialized first iteration. Off-by-one loop termination.
Related errors
- Empty stack. Nothing to pop
- Cannot pop from an empty stack.
- Cannot peek from an empty stack.
- Stack is empty, cannot pop element
- Stack is empty, cannot peek element
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/17c6bc777015dc3f.
Report an issue: GitHub.