gpt4 book ai didi

java - 插入到栈尾

转载 作者:行者123 更新时间:2023-12-02 12:36:08 25 4
gpt4 key购买 nike

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 插入堆栈,但是如果没有 return 语句,它将如何返回到上一个调用?

最佳答案

insert_at_bottom 是一个 void 函数。这种类型的函数不需要 return 语句。因此,一旦执行:

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

关于java - 插入到栈尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45130465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com