Java最小堆实现优先级队列迭代
我试图用这段代码来实现优先级队列。关于这个网站的实现有很多问题,但是考虑到你可以用多少种不同的方式编写代码来完成本质上相同的事情,在阅读了一些其他的例子之后,我仍然不知所措 这段代码中有一些遗漏的行,但我仅限于编辑四行标记的行,因此我发现自己在一个特定方面陷入了困境。我似乎不明白“数量”是如何递增的 根据我的理解,main创建了一个maxSize=5的新对象。然后调用insertItem方法,传递值130。这应该放在根目录中(我已经将queArray[quantity]=item;放在第一个空格中),此时insertItem方法退出,然后用下一个值再次调用。那么“数量”在什么时候增加呢?也许我遗漏了一些非常简单的东西,或者也许有另一种解决方法,像我这样的初学者可能不太清楚或者不知道 我认为您可能希望在初始if语句下增加数量,但这似乎不是一个选项,所以据我所知,else语句永远无法执行,因为数量不变。我知道我是错的,但我不知道怎么做,如果能得到一些帮助,我将不胜感激Java最小堆实现优先级队列迭代,java,implementation,priority-queue,Java,Implementation,Priority Queue,我试图用这段代码来实现优先级队列。关于这个网站的实现有很多问题,但是考虑到你可以用多少种不同的方式编写代码来完成本质上相同的事情,在阅读了一些其他的例子之后,我仍然不知所措 这段代码中有一些遗漏的行,但我仅限于编辑四行标记的行,因此我发现自己在一个特定方面陷入了困境。我似乎不明白“数量”是如何递增的 根据我的理解,main创建了一个maxSize=5的新对象。然后调用insertItem方法,传递值130。这应该放在根目录中(我已经将queArray[quantity]=item;放在第一个空格
public class Main {
/**
* @param args the command line arguments
*/
// array in sorted order, from max at 0 to min at size-1
private int maxSize;
private long[] queArray;
private int quantity;
public Main(int s) {
maxSize = s;
queArray = new long[maxSize];
quantity = 0;
}
public void insertItem(long item) {
int i;
if (quantity == 0)
__________; // insert at 0
else
{
for (i = quantity - 1; i >= 0; i--) // start at end,
{
if (item > queArray[i]) // if new item larger,
__________; // shift upward
else
// if smaller,
break; // done shifting
}
__________; // insert it
__________;
} // end else (quantity > 0)
}
public boolean PQEmpty(){
return (quantity == 0);
}
public long removeItemPQ(){
return queArray[--quantity];
}
public long peekMin(){
return queArray[quantity - 1];
}
public static void main(String[] args) {
Main thePQ = new Main(5);
thePQ.insertItem(130);
thePQ.insertItem(450);
thePQ.insertItem(110);
thePQ.insertItem(430);
thePQ.insertItem(280);
while (!thePQ.PQEmpty()) {
long item = thePQ.removeItemPQ();
System.out.print(item + " ");
}
System.out.println("");
}
}
这不是我推荐的样式,但您可以使用
queArray[quantity++]=item代码>谢谢你的建议。我也没有想到这一点。这当然不是我要做的,但是如果我从头开始编写代码,我还会做很多其他的事情,所以值得一试。现在我只需要想一想我是否能做到这一点。