使用Java从队列中删除var
Im-tring编写一个获取队列和参数(int)的函数,该函数删除队列中与参数相等的变量。这是我的密码:使用Java从队列中删除var,java,linked-list,Java,Linked List,Im-tring编写一个获取队列和参数(int)的函数,该函数删除队列中与参数相等的变量。这是我的密码: public static void remove_it( Queue <Integer> q, int x) { Queue <Integer> temp = new LinkedList<Integer>(); boolean found = false; if (!q.isEmpty()) { if
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());
}
}
}
publicstaticvoid移除它(队列q,intx)
{
Queue temp=new LinkedList();
布尔值=false;
如果(!q.isEmpty())
{
如果(q.peek()==x)
发现=真;
临时添加(q.remove());
}
布尔b;
如果(找到)
{
b=正确;
而(!temp.isEmpty())
{
if(temp.peek()==x&&b)
{
移除温度();
b=假;
}
其他的
q、 添加(临时删除());
}
}
}
但是,随时都可以删除队列的第一个变量。。。为什么会这样?要修复您的错误,请用一行代码替换它:
public static void remove_it(Queue <Integer> q, int x) {
q.remove(x);
}
publicstaticvoid移除它(队列q,intx){
q、 移除(x);
}
要修复您的错误,请用一行代码全部替换:
public static void remove_it(Queue <Integer> q, int x) {
q.remove(x);
}
publicstaticvoid移除它(队列q,intx){
q、 移除(x);
}
您是否已在IDE调试器中仔细查看了代码以查看发生了什么?您需要清理括号。此行:temp.add(q.remove())
每次都执行,因为它超出了前面的if
语句的范围。您可以在一行中完成整个任务:q.remove(新整数(x))代码>您是否已在IDE调试器中逐步查看代码以查看发生了什么?您需要清理括号。此行:temp.add(q.remove())
每次都执行,因为它超出了前面的if
语句的范围。您可以在一行中完成整个任务:q.remove(新整数(x))
您不需要显式地创建Integer
实例,是吗q.remove(x)
应该可以…@ErnestKiwele看到最近的评论添加到我的答案中。不是在队列上。队列有.remove()
和.remove(Object)
,没有基于索引的remove
像List
@ErnestKiwele我不知道为什么,但我在想List
。。。你说得很对。现在更简单了。您不需要显式地创建Integer
实例,是吗q.remove(x)
应该可以…@ErnestKiwele看到最近的评论添加到我的答案中。不是在队列上。队列有.remove()
和.remove(Object)
,没有基于索引的remove
像List
@ErnestKiwele我不知道为什么,但我在想List
。。。你说得很对。现在更简单了。