Inserting at the end of stack

16,979

Solution 1

The insert_at_bottom is a void function. This type of function does not need a return statement. So, as soon as it executes:

if(st.isEmpty())
  st.push(x);

It does not have anything to return, does not have anything else to execute and stops its recursion. To illustrate, the execution order would be something like this.

char a = st.peek();
st.pop();
char a2 = st.peek();
st.pop();
char a3 = st.peek();
st.pop();
st.push(x);
st.push(a3);
st.push(a2);
st.push(a);

Solution 2

if(st.isEmpty()){
  st.push(x);
  return;
}

I think we should add a return after adding the element because writing just return means control back cursor to calling function without executing futhure code. and because of the recursion we need a base case also

Share:
16,979
vvv
Author by

vvv

Updated on June 25, 2022

Comments

  • vvv
    vvv almost 2 years
    static void insert_at_bottom(char x){
    
        if(st.isEmpty())
            st.push(x);
    
        else{
            /* All items are held in Function Call Stack until we
               reach end of the stack. When the stack becomes
               empty, the st.size() becomes 0, the
               above if part is executed and the item is inserted
               at the bottom */
    
            char a = st.peek();
            st.pop();
            insert_at_bottom(x);
    
            //push all the items held in Function Call Stack
            //once the item is inserted at the bottom
            st.push(a);
        }
    }
    

    In the above code, I have a question about this step:

    if(st.isEmpty())
            st.push(x);
    

    Don't we require a return statement after st.push(x)?

    I mean that in recursion stack when that condition is satisfied i.e. when the stack is empty, it would push x into the stack, but how would it return to the previous call without the return statement?