首先,我觉得我应该提到这是一项作业。我并不是在寻找直接的代码答案,只是为了指出正确的方向。我们被要求在链表中实现优先级队列。
我正在努力编写 insert() 函数的第一部分。在代码中我尝试检查是否head
包含任何内容,如果没有则设置为head
to pqItem
。它执行此操作,但是当再次调用 insert 进行第二次插入时,它无法识别head
已经有一个PQueueItem
在其中并且只是覆盖head
而不是忽略if (this.head == null)
。难道我没设置head
正确吗?
PQueue类
package ci284.ass1.pqueue;
public class PQueue<T> {
private PQueueItem<T> head;
public static enum ORDER {
ASC, DESC;
}
public static ORDER DEFAULT_ORDER;
private ORDER order;
public PQueue() {
this.order = DEFAULT_ORDER;
head = null;
}
...
public void insert(T data, int priority) {
PQueueItem<T> pqItem = new PQueueItem<T>(data, priority);
PQueueItem<T> temp;
PQueueItem<T> prev;
System.out.println("This is pqItem " + pqItem);
if (this.order == ORDER.DESC || this.order == DEFAULT_ORDER){
if (this.head != null){
System.out.println("Not null " + head);
if (priority <= head.getPriority()){
}
else if (priority > head.getPriority()){
prev = head;
System.out.println(prev);
head.setNext(head);
prev = pqItem;
System.out.println(prev);
}
}
if (this.head == null){
System.out.println("Null " + head);
this.head = pqItem;
System.out.println("Null " + head);
}
}
}
PQueueItem 类
package ci284.ass1.pqueue;
public class PQueueItem<T> {
private int priority;
private T data;
private PQueueItem<T> next;
public PQueueItem(T data, int priority) {
this.data = data;
this.priority = priority;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public PQueueItem<T> getNext() {
return next;
}
public void setNext(PQueueItem<T> next) {
this.next = next;
}
public String toString() {
return String.format("[%s,%d]", data.toString(), priority);
}
}
插入的 JUnit 测试
@Test
public void testInsertStart(){
PQueue<String> pq = new PQueue<String>();
pq.insert("1",2);
String head = pq.pop();
assertEquals(head, "1");
System.out.println("Worked");
pq.insert("Hiya",3);
assertEquals(head, "Hiya");
}
测试返回:
org.junit.ComparisonFailure: expected:<1> but was:<Hiya>
控制台显示:
This is pqItem [1,2]
Null null
Null [1,2]
Worked
This is pqItem [Hiya,3]
Null null
Null [Hiya,3]