VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-a-stack/

⇱ Reverse a Stack - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse a Stack

Last Updated : 20 Feb, 2026

Given a stack st[], Reverse the stack so that the top element becomes the bottom and the bottom element becomes the top, while preserving the order of the remaining elements accordingly.

Note: The input array represents the stack from bottom to top (last element is the top). The output is displayed by printing elements from top to bottom after reversal.

Example: 

Input: st[] = [1, 2, 3, 4]
Output: [1, 2, 3, 4]
Explanation:

👁 3

Input: st[] = [3, 2, 1]
Output: [3, 2, 1]
Explanation:

👁 4

[Approach 1] Recursive Approach

The idea is to use the recursion to reverse the given stack.

  • First, we keep removing elements from the stack until stack becomes empty.
  • Once the stack is empty, we start going back in the recursion. At each step, instead of placing the element back on top, we insert it at the bottom of the stack.
  • To insert an element at the bottom, we recursively pop all elements, push the current element, and then put the popped elements back.

This way we will ensuring that the element that was originally at the top moves to the bottom, and gradually the entire stack gets reversed.


Output
1 2 3 4 

Time Complexity: O(n2)
Auxiliary Space: O(n), due to recursion stack

[Approach 2] Iterative Approach - O(n) Time and O(n) Space

We use an auxiliary stack to hold elements while popping them from the original stack. Since stacks are LIFO, pushing all elements into the auxiliary stack will naturally reverse their order. Finally, we replace the original stack with the auxiliary stack.


Output
1 2 3 4 
Comment
Article Tags: