Reverse a stack using recursion - cook the code

Thursday, 28 December 2017

Reverse a stack using recursion




Reverse a stack using recursion


Write a program to reverse a stack using recursion. You are not allowed to use loop constructs like while, for..etc, and you can only use the following ADT functions on Stack S:
isEmpty(S)
push(S)
pop(S)
The idea of the solution is to hold all values in Function Call Stack until the stack becomes empty. When the stack becomes empty, insert all held items one by one at the bottom of the stack.
For example, let the input stack be
    1  <-- top
    2
    3
    4   
First 4 is inserted at the bottom.
    4 <-- top

Then 3 is inserted at the bottom
    4 <-- top    
    3

Then 2 is inserted at the bottom
    4 <-- top    
    3 
    2
     
Then 1 is inserted at the bottom
    4 <-- top    
    3 
    2
    1
So we need a function that inserts at the bottom of a stack using the above given basic stack function.
void insertAtBottom((): First pops all stack items and stores the popped item in function call stack using recursion. And when stack becomes empty, pushes new item and all items stored in call stack.
void reverse(): This function mainly uses insertAtBottom() to pop all items one by one and insert the popped items at the bottom.

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.
    }

No comments:

Post a Comment