【问题标题】:Pop elements in stack until some element弹出堆栈中的元素,直到某个元素
【发布时间】:2018-05-02 04:35:30
【问题描述】:

我有这样的代码:

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,它显示输出为[new,new,new1。我只需要[new,new]]

【问题讨论】:

    标签: java stack


    【解决方案1】:

    换句话说, 弹出太多元素。 要检查下一个元素是否不是“新的”, 没有实际删除该元素, 您需要使用peek() 而不是pop()

    另外, 为了避免在所有元素都是“新”的情况下使程序崩溃, 您需要反复检查堆栈是否为空。

    while (!stack.empty() && !stack.peek().equals("new")) {
        System.out.println("pop element " + stack.pop());
    }
    System.out.println("STACK :" + stack);
    

    【讨论】:

      猜你喜欢
      • 2016-06-29
      • 1970-01-01
      • 2010-10-28
      • 2016-09-05
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      相关资源
      最近更新 更多