2017-07-16 67 views
0
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); 
    } 
} 

在上面的代码的末尾插入,我有一个关于这一步的问题:在堆栈

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

难道我们需要st.push(x)后return语句?

我的意思是说,在递归堆栈中,当条件满足时,即堆栈为空时,它会将x推入堆栈,但是如何返回前一个没有返回语句的调用?

+0

这是什么语言? – melpomene

+0

Java语言它是 – vijay

+0

推是最后的声明,因为只有'if'语句的'else'部分如下。所以它在呼叫站点返回。 –

回答

1

insert_at_bottom是一个void函数。这种类型的函数不需要返回语句。所以,只要它执行:

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

它不会有什么回报,没有别的来执行和停止它的递归。为了说明,执行顺序将是这样的。

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);