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

how to remove specific element from stack?

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

    }