VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reversing-a-stack-with-the-help-of-another-empty-stack/

⇱ Reversing a Stack with the help of another empty Stack - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reversing a Stack with the help of another empty Stack

Last Updated : 23 Jul, 2025

Given a Stack consisting of N elements, the task is to reverse the Stack using an extra stack.

Examples:

Input: stack = {1, 2, 3, 4, 5} 
Output:





Explanation:
Input Stack: 





Reversed Stack: 




5

Input: stack = {1, 3, 5, 4, 2} 
Output:




2

Approach 1: Follow the steps below to solve the problem:

Below is the implementation of the above approach.


Output
1 2 3 4 5

Time Complexity: O(N2
Auxiliary Space: O(N)


Approach 2: Follow the steps below to solve the problem:

  • Initialize an empty stack called ans.
  • Pop the top element of the given stack S and push it into the stack ans.
  • Return the stack ans, which will contain the reversed elements of the stack S.

Below is the implementation of the above approach.


Output
1 2 3 4 5 

Time Complexity: O(N) 
Auxiliary Space: O(N)

Comment
Article Tags: