Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To reverse a stack, make its bottom element the new top and its original top the new bottom. For example, a stack with top-to-bottom order 4, 3, 2, 1 becomes 1, 2, 3, 4. In modern Java, represent a stack with Deque<E> and ArrayDeque<E>. The recursive method below is useful for learning; an iterative method with a temporary deque avoids recursion-depth limits.

Define the stack order first

A stack follows last-in, first-out (LIFO): push(e) adds an element to the top, pop() removes and returns the top element, and peek() reads it without removing it. In this guide, “top to bottom” names the logical order, independently of how a collection happens to print itself.

For example:

Before, top → bottom: 4, 3, 2, 1
After,  top → bottom: 1, 2, 3, 4

This is an in-place reversal: the original stack is changed. It is different from printing elements in reverse order or making a reverse-ordered view.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Deque for a Java stack

For new code, declare the Deque interface and create an ArrayDeque:

import java.util.ArrayDeque;
import java.util.Deque;

Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);

Each push adds to the top, so the logical order is now 4, 3, 2, 1. With ArrayDeque, push and pop operate at the front. Oracle’s Java API documentation recommends using Deque implementations in preference to the legacy Stack class. Stack remains available; this is a recommendation, not a removal.

Recursive reversal

The key challenge is putting a saved element at the bottom. The method removes the top, reverses what remains, then inserts the saved value at the bottom.

import java.util.ArrayDeque;
import java.util.Deque;

public class ReverseStack {
    public static <E> void reverse(Deque<E> stack) {
        if (stack.isEmpty()) {
            return;
        }

        E top = stack.pop();
        reverse(stack);
        insertAtBottom(stack, top);
    }

    private static <E> void insertAtBottom(Deque<E> stack, E value) {
        if (stack.isEmpty()) {
            stack.push(value);
            return;
        }

        E top = stack.pop();
        insertAtBottom(stack, value);
        stack.push(top);
    }

    public static void main(String[] args) {
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);

        reverse(stack);

        // ArrayDeque displays encounter order; here the front is the top.
        System.out.println("Top to bottom: " + stack);
    }
}

Output:

Top to bottom: [1, 2, 3, 4]

How the recursion works

Starting with top-to-bottom order 4, 3, 2, 1, the recursive calls pop 4, then 3, then 2, then 1, leaving an empty stack. As the calls return, each saved item is inserted at the bottom:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Insert 1 into empty stack → 1
Insert 2 at bottom       → 1, 2
Insert 3 at bottom       → 1, 2, 3
Insert 4 at bottom       → 1, 2, 3, 4

The empty-stack check is the base case, so an empty input returns normally. A one-element stack also works without a special case and remains unchanged.

Complexity and limits

This standard recursive method takes O(n²) time and O(n) auxiliary space. Each insertion at the bottom may pop and restore the elements already in the stack; doing that at each recursive level produces quadratic work. The recursion also uses the Java call stack, so a very large input can cause StackOverflowError.

Iterative reversal with a temporary deque

When stack operations are required but recursion is undesirable, use a second deque. This version explicitly transfers elements from one end to another, making the resulting order clear:

public static <E> void reverseIteratively(Deque<E> stack) {
    Deque<E> temporary = new ArrayDeque<>();

    while (!stack.isEmpty()) {
        temporary.addLast(stack.pop());
    }

    while (!temporary.isEmpty()) {
        stack.push(temporary.removeLast());
    }
}

For an original order of 4, 3, 2, 1 (top to bottom), the first loop puts 4, 3, 2, 1 into the temporary deque from first to last. The second loop removes from its last end—1 first—and pushes each value onto the original stack. The final top-to-bottom order is 1, 2, 3, 4.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This method takes O(n) time and O(n) extra space. It avoids recursion-depth limits, though it still needs temporary storage proportional to the number of elements.

If the data is actually a List

If the collection is a list rather than a stack that must be handled through stack operations, Collections.reverse is simpler:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

List<Integer> values = new ArrayList<>(List.of(1, 2, 3, 4));
Collections.reverse(values);
System.out.println(values); // [4, 3, 2, 1]

Collections.reverse(List<?>) mutates the list in place and runs in linear time. It may throw UnsupportedOperationException if the list does not support replacement. For example, make a mutable copy before reversing a list created with List.of. See the Collections API documentation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Read in reverse without changing the collection

If you only need to visit elements in reverse order, do not reverse the stack. For a deque, descendingIterator() traverses from the last element toward the first:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
var iterator = stack.descendingIterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

That changes traversal order, not the deque’s contents. Likewise, Java 21 and later provide List.reversed(), which returns a reverse-ordered view rather than an independent copy:

Best Value
Sale
Data Structures and Algorithms Made Easy in Java: Data Structure and Algorithmic Puzzles
  • Data Structure and Algorithmic Puzzles
  • By Careermonk Publications
  • It ensures you get the best usage for a longer period
for (int value : values.reversed()) {
    System.out.println(value);
}

Whether changes through a view affect its backing collection depends on the collection’s view contract. Consult the List API documentation for the Java version in use.

Common edge cases

  • Empty stack: both methods return normally; the recursive base case or iterative loop handles it.
  • One element: its order cannot change, and both methods leave it in place.
  • Duplicates: reversal preserves every occurrence. For example, 3, 1, 3, 2 becomes 2, 3, 1, 3. Do not use a set, which would discard duplicates.
  • Null values: ArrayDeque does not permit null; push(null) fails. Choose another collection if null elements are genuinely required, or avoid nulls in the stack.
  • Empty pops: check isEmpty() before pop(). ArrayDeque.pop() throws NoSuchElementException when empty; Stack.pop() throws EmptyStackException.
  • Very large inputs: prefer the iterative method if recursion depth could become a problem.

To check which JDK is installed, run java --version and javac --version. The recursive and iterative examples use long-standing Deque/ArrayDeque APIs; List.reversed() requires Java 21 or later.

Quick Recap

SaleBestseller No. 1
SaleBestseller No. 2
SaleBestseller No. 3
SaleBestseller No. 5
Data Structures and Algorithms Made Easy in Java: Data Structure and Algorithmic Puzzles
Data Structures and Algorithms Made Easy in Java: Data Structure and Algorithmic Puzzles
Data Structure and Algorithmic Puzzles; By Careermonk Publications; It ensures you get the best usage for a longer period
$30.97

Which method should you choose?

  • Use recursive bottom insertion to learn recursion or explain the classic interview problem; remember its O(n²) time and call-stack cost.
  • Use the iterative temporary-deque method when the task requires stack operations and you want linear time without recursive calls.
  • Use Collections.reverse when the data is a mutable list and list operations are appropriate.
  • Use a reverse iterator or view when the requirement is read-only reverse traversal, not mutation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.