我有这样的代码:
public static void main(String[] args) throws Exception {
String popElement ;
Stack<String> stack = new Stack();
stack.push( "new" );
stack.push( "new" );
stack.push( "new1" );
stack.push( "new2" );
if(! stack.empty() )
{
do
{
popElement = stack.pop();
System.out.println( "pop element "+popElement );
}while (popElement.equals( "new" ));
}
System.out.println( "STACK :"+stack );
我想弹出堆栈直到新的,我需要堆栈输出为 [new,new]
.. 但我的代码只弹出 new2
,它显示输出为 [新,新,新 1
。我只需要 [new,new]]
。
最佳答案
换句话说,
弹出了太多元素。
要检查下一个元素不是“新元素”,
没有实际删除该元素,
您需要使用 peek()
而不是 pop()
。
此外, 为了避免在所有元素都是“新元素”的情况下使程序崩溃, 需要反复检查栈是否为空。
while (!stack.empty() && !stack.peek().equals("new")) {
System.out.println("pop element " + stack.pop());
}
System.out.println("STACK :" + stack);
关于java - 弹出堆栈中的元素直到某个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47366926/