Reverse a stack using

How to Reverse a stack using recursion.

I think this article can help you.

1 Like

You can reverse a stack using recursion by performing PUSH() and POP() operations only.
To reverse a stack means, we have to move-

element at top position to bottom position

element at second top position to second bottom position, and so on

So ,create a recursive function which will give you elements one by one in order and an another recursive function which will insert an element at bottom of the stack every time.

    stack<int> st;
    void insert_at_bottom(int curr)
    {
        if(st.empty())   //stack is empty means bottom of the stack,insert the current element
            st.push(curr);
        else
        {
            int el=st.top();
            st.pop();
            insert_at_bottom(curr);
            st.push(el);
        }
    }
    void reverse()
    {
        if(st.empty())
            return;
        int d=st.top();
        st.pop();
        reverse();
        insert_at_bottom(d); //Inserting an element at bottom of the stack.
    }

Hope ,this is helpful.
If you still did not get anything ,feel free to ask…

1 Like

This is a standard algo question. Refer to this link for explanation.