如何从堆栈中删除特定元素?

问题描述

例如,如何从堆栈中删除元素 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());
  }


  }

解决方法

所以你应该将 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());
        }

    }