实现Java优先级队列 [英] Implementing Java Priority Queue
问题描述
public class PriorityQueue<T> {
private PriorityNode<T> head, tail;
private int numItems;
public PriorityQueue(){
numItems = 0;
head=null;
tail=null;
}
public void add(int priority, T value){
PriorityNode<T> newNode = new PriorityNode<T>(priority,value);
if(numItems == 0){
head = newNode;
tail = newNode;
}
else{
head.setNext(newNode);
head = newNode;
}
}
}
其中PriorityNode定义为:
Where PriorityNode is defined as:
public class PriorityNode<T> implements Comparable<T> {
private T value;
private PriorityNode<T> next;
private int priority;
public PriorityNode(int priority,T newValue){
value = newValue;
next = null;
priority = 0;
}
public PriorityNode(T newValue){
value = newValue;
next = null;
priority = 0;
}
public void setPriority(int priority){
this.priority = priority;
}
public int getPriority(){
return this.priority;
}
public T getValue(){
return value;
}
public PriorityNode<T> getNext(){
return next;
}
public void setNext(PriorityNode<T> nextNode){
this.next = nextNode;
}
public void setValue(T newValue){
value = newValue;
}
@Override
public int compareTo(int pri) {
// TODO Auto-generated method stub
if(this.priority<pri){
return -1;
}
else if(this.priority == pri){
return 0;
}
else{
return 1;
}
}
}
我在使用比较器并实现优先级队列时遇到了很多困难 - 请指出我正确的方向。
I'm having a lot of difficulty using the Comparator here and implementing a priority queue - please point me in the right direction.
推荐答案
关于比较器的实施,实施 比较者< T>
或 可比较< T>
界面需要 public int compareTo(T o)
要覆盖的方法。
Regarding the implementing of the comparator, implementing the Comparator<T>
or Comparable<T>
interface requires the public int compareTo(T o)
method to be overridden.
在给出的示例代码中, compareTo(T)
方法未被覆盖( compareTo(int)
方法已定义,但不方法签名相同),因此,它可能会导致编译器错误。
In the example code given, the compareTo(T)
method is not overridden (the compareTo(int)
method is defined, but that is not the same method signature), therefore, it will probably lead to a compiler error.
这篇关于实现Java优先级队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!