我正在尝试编写一个获取队列和参数(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());
}
}
}
但是,它会随时删除队列的第一个变量...这是为什么?
要修复您的错误,请将其全部替换为一行:
public static void remove_it(Queue <Integer> q, int x) {
q.remove(x);
}