Stack reverse using recursion

Can you just explain once how this works??

In this problem you need to reverse the elements inside the stack using recursion. You cannot use any other stack other than this.
We can use recursion to solve problems which can be broken down to SAME problems but of smaller sizes.

Example in this one, let say we have N elements and we are coding a recursive function with name “reverseStackRecursive”

Then we need to divide our problem to SAME problems but of smaller size, we can do something like

Pop the topmost element
call reverseStackRecursive(n-1) // Ask our function to reverse the n - 1 elements (SAME problem but of smaller size)
Insert the popped element at the bottom
Example lets say we have in the stack
5
4
3
2
1

Pop the topmost element - 5
Now stack is 4 3 2 1 (Rightmost is the bottom most element)
call reverseStackRecursive(n-1)
Now stack is 1 2 3 4
Insert the popped element at the bottom
Now stack is 1 2 3 4 5

Now internally when call for 4 3 2 1 was given as the recursive case, 4 gets popped, gives call for 3 2 1 to be reversed, 3 gets popped calls for 2 1, 2 gets popped, calls for 1, now 1 gets popped, stack empty so nothing to be done, just insert popped element(1) at bottom, so stack is 1, now for 2 as popped element, remaining stack which is 1 has been reversed, so insert 2 at bottom, stack becomes 1 2, now for 3 as popped element, remaining stack which is 1 2 has been reversed, so insert 3 at bottom, stack becomes 1 2 3, now for 4 as popped element, remaining stack which is 1 2 3 has been reversed, so insert 4 at bottom, stack becomes 1 2 3 4, that’s how we’ve gotten 1 2 3 4 from reversing 4 3 2 1, and hence insert 5 at bottom of 1 2 3 4 and ans stack becomes 1 2 3 4 5

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.