please give a dry run of the algorithm as Im not able to do it
About the stack reverse
Hey @aslesha.j7
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
i have a doubt the even if we do no return something the function after executing its all statements returns the control back to the calling function right?
when we use return we immediately transfer the control to the calling function without performing the rest of the executions in the called function after the return statement right?