Reverse Stack using Recursion
This article will explain how to reverse the stack elements using recursion without using others loop statements like while, for, etc. We can achieve this by holding all values in the function call stack until the stack becomes empty and check whether the stack is empty. When the stack becomes empty, we will push all hold items at the bottom of the stack one by one.
Here are the functions which will be used in this process:
void insertAtBottom(int num): This function is used to insert or push an element at the bottom of the stack using recursion.
void reverse(): We will use this function for popping the top element from the stack and store this element in the function stack. After this, the function will recursively call itself to reverse the rest of the elements of the stack, and also, it will call insertAtBottom function to push or insert the top element at the bottom of the stack.
Example
Output Stack:
Firstly we will insert 3 at the bottom of the stack.
3 < — Top
Then, we will insert 5 at the bottom of the stack.
3 < — Top
5
Then, we will insert 7 at the bottom of the stack.
3 < — Top
5
7
Then, we will insert 9 at the bottom of the stack.
3 < — Top
5
7
9