![]() |
VOOZH | about |
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 1Input: elements present in stack from top to bottom 1 2 3
Output: 3 2 1
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:
Below is the implementation of the above approach:
Original Stack 1 2 3 4 Reversed Stack 1 2 3 4
Time Complexity: O(N2).
Auxiliary Space: O(N) use of Stack