从队列中删除并添加到另一个队列时遇到问题
Having trouble removing from a queue and adding to another
我有一个包含许多字符串和整数的输入文件。
例如
废话 40
你好 10
asdf 20
等...
我已经将它们读入队列以保留它们。每当 int i 等于我的数据文件中的 int 时,我需要将它们从队列中取出并将其添加到优先级队列中。
这是我目前所拥有的..
for(int i = 0; i<=50; i++)
{
Object x = normalQueue.Dequeue(); //this makes x equal the line of the data file dequeued.
if(i == x.secondint) //secondint is the Objects method that gets the integer in the data file
{
PQueue.Insert(x); //Inserts x to PQueue if i = the second int in the data file
}
else
{
normalQueue.Enqueue(x); //adds x back to queue1
normalQueue.SwitchEnds(); //Swaps the 1st and last node
}
}
我遇到的问题是它只打印出数据文件的 2 个文件。
我不太确定当 运行 你的代码时你打算发生什么,但会发生什么是这样的:
给定以下输入:
blah 40
hello 10
asdf 20
(我假设你在从文件读取时将元素添加到队列的后面,所以数据文件的顺序将被保留)
在循环的前 40 次迭代中,您从 Queue1
中取出 "blah 40"
,将 "blah 40"
添加回 Queue1
,然后交换 "blah 40"
使用 "asdf 20"
或 "hello 10"
(取决于您经历了多少次迭代),以便 "blah 40"
再次位于 Queue1
.
的开头
在循环的第 41 次迭代中,i
将变为 40,您将 "blah 40"
插入 Queue2
。
在第 42 次迭代中,直到循环的最后一次迭代,除了将 Queue1
改组之外,什么都没有真正完成,因为 i
在 "blah 40"
被删除之前不是 10 或 20,所以在循环结束时 Queue1
包含 "hello 10"
和 "asdf 20"
,而 Queue2
包含 "blah 40"
。
我意识到这个演练可能有点混乱,但尝试在每次迭代后打印出两个队列的内容,它应该会变得更清楚。
编辑:
在我看来,您想要实现的目标是对第二个整数(即 40、10 和 20)进行优先排序,这样当您遍历 Queue2
并删除一个和一个元素时,它们会像这样打印出来:
"hello 10"
"asdf 20"
"blah 40"
(或相反)。
如果是这种情况,那么根本不需要 Queue1
,您只需要确保为您的优先级队列提供一个自定义比较器,该比较器根据第二个整数对您的对象进行排序。 (或者,您可以在自定义对象中实现类似的接口)。
示例比较器:
new Comparator<YourCustomObject>()
{
@Override
public int compare(YourCustomObject o1, YourCustomObject o2)
{
return Integer.compare(o1.secondint, o2.secondint);
}
}
我有一个包含许多字符串和整数的输入文件。
例如
废话 40
你好 10
asdf 20
等...
我已经将它们读入队列以保留它们。每当 int i 等于我的数据文件中的 int 时,我需要将它们从队列中取出并将其添加到优先级队列中。
这是我目前所拥有的..
for(int i = 0; i<=50; i++)
{
Object x = normalQueue.Dequeue(); //this makes x equal the line of the data file dequeued.
if(i == x.secondint) //secondint is the Objects method that gets the integer in the data file
{
PQueue.Insert(x); //Inserts x to PQueue if i = the second int in the data file
}
else
{
normalQueue.Enqueue(x); //adds x back to queue1
normalQueue.SwitchEnds(); //Swaps the 1st and last node
}
}
我遇到的问题是它只打印出数据文件的 2 个文件。
我不太确定当 运行 你的代码时你打算发生什么,但会发生什么是这样的:
给定以下输入:
blah 40
hello 10
asdf 20
(我假设你在从文件读取时将元素添加到队列的后面,所以数据文件的顺序将被保留)
在循环的前 40 次迭代中,您从 Queue1
中取出 "blah 40"
,将 "blah 40"
添加回 Queue1
,然后交换 "blah 40"
使用 "asdf 20"
或 "hello 10"
(取决于您经历了多少次迭代),以便 "blah 40"
再次位于 Queue1
.
在循环的第 41 次迭代中,i
将变为 40,您将 "blah 40"
插入 Queue2
。
在第 42 次迭代中,直到循环的最后一次迭代,除了将 Queue1
改组之外,什么都没有真正完成,因为 i
在 "blah 40"
被删除之前不是 10 或 20,所以在循环结束时 Queue1
包含 "hello 10"
和 "asdf 20"
,而 Queue2
包含 "blah 40"
。
我意识到这个演练可能有点混乱,但尝试在每次迭代后打印出两个队列的内容,它应该会变得更清楚。
编辑:
在我看来,您想要实现的目标是对第二个整数(即 40、10 和 20)进行优先排序,这样当您遍历 Queue2
并删除一个和一个元素时,它们会像这样打印出来:
"hello 10"
"asdf 20"
"blah 40"
(或相反)。
如果是这种情况,那么根本不需要 Queue1
,您只需要确保为您的优先级队列提供一个自定义比较器,该比较器根据第二个整数对您的对象进行排序。 (或者,您可以在自定义对象中实现类似的接口)。
示例比较器:
new Comparator<YourCustomObject>()
{
@Override
public int compare(YourCustomObject o1, YourCustomObject o2)
{
return Integer.compare(o1.secondint, o2.secondint);
}
}