首页 > 解决方案 > 使用 Java 从队列中删除 var

问题描述

我想写一个获取队列和参数(int)的函数,该函数删除队列中等于参数的var。这是我的代码:

 public static void remove_it( Queue <Integer> q, int x)
{

    Queue <Integer> temp = new LinkedList<Integer>();
    boolean found = false;
    if (!q.isEmpty())
    {
        if (q.peek()==x)
            found = true;
        temp.add(q.remove());
    }

   boolean b;
    if (found)
    {
     b = true;

    while (!temp.isEmpty())
    {
        if (temp.peek() == x  && b)
            {
                temp.remove();
                b = false;
            }
        else
            q.add(temp.remove());
    }
   }

    }

但是,它随时删除队列的第一个变量......这是为什么?

标签: javalinked-list

解决方案


要修复您的错误,请将其全部替换为一行:

public static void remove_it(Queue <Integer> q, int x) {
    q.remove(x);
}

推荐阅读