gpt4 book ai didi

java - 不使用 peek() 从堆栈中删除元素

转载 作者:行者123 更新时间:2023-12-01 18:37:23 25 4
gpt4 key购买 nike

我有一个 Student 对象的堆栈 s 和一个 Student 对象 e。如何在不使用 s.peek() 方法的情况下删除最上面出现的 e 上方的堆栈中的所有元素?

最佳答案

弹出直到遇到e,然后再次推送e

Student top = null;
while(!s.isEmpty() && !e.equals(top)){
top = s.pop();
}
if(e.equals(top)) {
s.push(top);
} else {
// e was not on the stack
}

关于java - 不使用 peek() 从堆栈中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21340660/

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