TheAlgorithms/Java · error · NoSuchElementException

Empty stack. Nothing to pop

Error message

Empty stack. Nothing to pop

What it means

Thrown by StackOfLinkedList.pop() when the stack's size is 0. pop() dereferences head to read head.data and advance to head.next, so on an empty stack it would throw NullPointerException. The NoSuchElementException signals that there is no element to remove — a caller logic error.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java:76

     * @return <tt>true</tt> if the element is added successfully
     */
    public boolean push(int x) {
        Node newNode = new Node(x);
        newNode.next = head;
        head = newNode;
        size++;
        return true;
    }

    /**
     * Removes and returns the top element of the stack.
     *
     * @return the element at the top of the stack
     * @throws NoSuchElementException if the stack is empty
     */
    public int pop() {
        if (size == 0) {
            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");

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check size==0 (or use a provided isEmpty() method) before pop().
  2. Iterate with while (stack.size() > 0) rather than a fixed count.
  3. Catch NoSuchElementException if draining past empty is an expected branch.
  4. Audit for unbalanced push/pop at the call sites.

Example fix

// before
while (count-- > 0) {
    int v = stack.pop();
}
// after
while (stack.size() > 0) {
    int v = stack.pop();
}
Defensive patterns

Strategy: validation

Validate before calling

while (stack.size() > 0) {
    int v = stack.pop();
}

Prevention

When it happens

Trigger: Calling pop() on a newly constructed StackOfLinkedList (size==0). Calling pop() after the stack has been emptied. Popping in a loop without checking size.

Common situations: Unbalanced push/pop in graph traversals or expression evaluation. Reusing a stack instance without state verification. Off-by-one loop bounds.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/78ab4c100fc923ad. Report an issue: GitHub.