Reverse stack using recursion

can you please tell me how this function work

void reverse(stack &st) //passed by ref as to reflect change in main
{
if(st.empty())
{
return;
}
else
{
int x=st.top();
st.pop();
reverse(st);
insert(st,x);
}
}

Hello @Ankit_123,

To understand the solution to this problem.
You need to understand the operation of the insert function also.

reverse() function:

  1. this function stores the top element of the stack in a temporary variable and then pops it out of the stack.
  2. After that, it goes to the next recursive call of the reverse() function.
  3. In the new recursive call, it performs the function specified in point 1. and 2.
  4. This will repeat until stack becomes empty i.e. the base case.
  5. After reaching the base case, the programs start leaving the recursive calls of the reverse() function in the order opposite to the order in which the calls were made.
  6. After returning from the base case, it calls the insert() function and returns from the function.
  7. point 6 is repeated until it returns from all the function calls.

insert() function: To insert the element x at the bottom of the stack st.

Hope, this would help.

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.