VOOZH about

URL: https://www.geeksforgeeks.org/c/c-program-to-reverse-a-stack-using-recursion/

⇱ C Program to Reverse a Stack using Recursion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C Program to Reverse a Stack using Recursion

Last Updated : 23 Jul, 2025

Write a program to reverse a stack using recursion, without using any loop.

Example: 

Input: elements present in stack from top to bottom 1 2 3 4 
Output: 4 3 2 1 

Input: elements present in stack from top to bottom 1 2 3
Output: 3 2 1

Recommended Practice

The idea of the solution is to hold all values in Function Call Stack until the stack becomes empty. When the stack becomes empty, insert all held items one by one at the bottom of the stack. 

Illustration: 

Below is the illustration of the above approach

  • Let given stack be
       1        
       2
       3
       4
  • After all calls of reverse,  4 will be passed to function insert at bottom, after that 4 will pushed to the stack when stack is empty
        4       
  • Then 3 will be passed to function insert at bottom , it will check if the stack is empty or not if not then pop all the elements back and insert 3 and then push other elements back.
                                                                                               
       4       
       3
  • Then 2 will be passed to function insert at bottom , it will check if the stack is empty or not if not then pop all the elements back and insert 2 and then push other elements back.
      4       
      3
      2
  • Then 1 will be passed to function insert at bottom , it will check if the stack is empty or not if not then pop all the elements back and insert 1 and then push other elements back.
     
      4       
      3
      2
      1

 Follow the steps mentioned below to implement the idea:

  • Create a stack and push all the elements in it.
  • Call reverse(), which will pop all the elements from the stack and pass the popped element to function insert_at_bottom()
  • Whenever insert_at_bottom() is called it will insert the passed element at the bottom of the stack.
  • Print the stack                             

Below is the implementation of the above approach:


Output
Original Stack
1 2 3 4 
Reversed Stack
1 2 3 4 

Time Complexity: O(N2). 
Auxiliary Space: O(N) use of Stack 

Comment
Article Tags: