使用 Java 从队列中删除 var

问题描述 投票:0回答:1

我正在尝试编写一个获取队列和参数(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());
        }
    }

}

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

java linked-list
1个回答
5
投票

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

public static void remove_it(Queue <Integer> q, int x) {
    q.remove(x);
}
© www.soinside.com 2019 - 2024. All rights reserved.