【问题标题】:how to remove specific element from stack?如何从堆栈中删除特定元素?
【发布时间】:2021-05-27 02:02:06
【问题描述】:

例如,如何从堆栈中删除元素 1 2 3 4 5 6 删除(列表,3) 删除后栈是这样的 1 2 3

public static void removeElements(LinkedStack<Integer> list , int x){

    LinkedStack<Integer> list2  = new LinkedStack<>();
 
 
    
  while(!list.isEmpty()){
   int temp = list.pop();
    
    if(temp == x){

      list.pop();
    }
    list2.push(temp);
    
  }
  
  while(!list2.isEmpty()){
      list.push(list2.pop());
  }


  }

【问题讨论】:

    标签: java data-structures stack


    【解决方案1】:

    所以你应该将 x 添加到第二个列表中并添加如下元素:

    public static void removeElements(LinkedStack<Integer> list, int x) {
    
            LinkedStack<Integer> list2 = new LinkedStack<>();
            boolean found=false;
    
            while (!list.isEmpty()) {
                int temp = list.pop();
    
                if (temp == x || found) {
                    found=true;
    
                    list2.push(temp);
                }
            }
    
            while (!list2.isEmpty()) {
                list.push(list2.pop());
            }
    
        }
    

    【讨论】:

    • 谢谢你,先生,但我希望它删除元素,直到它到达指定的元素,当它到达指定的元素时,它会给我一个没有删除元素的列表
    • 我已编辑我的答案以考虑您的解释
    • 对不起,整件事仍然毫无意义。如果x 设置为堆栈上不存在的值,则堆栈中的所有值都将被删除。所以堆栈list2 是多余的。问题是如何从堆栈中删除特定元素? 但恰恰是那个元素3 没有被删除。最后,我会调用LinkedStack 堆栈而不是列表。
    猜你喜欢
    • 2013-11-07
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 2014-12-04
    相关资源
    最近更新 更多