Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting at the end of stack

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?

like image 337
vvv Avatar asked Jul 16 '17 15:07

vvv


2 Answers

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);
like image 169
karran Avatar answered Oct 20 '22 21:10

karran


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

like image 1
Nishant Patel Avatar answered Oct 20 '22 21:10

Nishant Patel