我尝试使用链接列表在java中创建优先级队列,但有些东西不起作用。我理解优先级队列的一般功能,但是对于java来说,我是一个完整的初学者。我看过其他例子,似乎无法找到我的错误。有什么建议?我注意到的一件事是使用类型或者其他什么,但我不确定那是什么。
头等舱:
public class Node { //Node class structure
int data; //data contained in Node
Node next; //pointer to Next Node
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
第二课:
import work.Node;
//basic set-up of a singly linked list
public class SLList{
Node head; //head of SLList
Node tail; //tail of SLList
int n; //number of elements in SLList
}
第三课:
import work.Node;
public class PriorityQueue extends SLList{
//add a new node
public void add(int x){
Node y = new Node();
y.data = x;
if (tail == null){ //if there is no existing tail, thus an empty list
tail = y; //assign tail and head as new node y
head = y;
}
else if (y.data < head.data){ //if new node y is the smallest element, thus highest priority
y.next = head; //assign y's next to be current head of queue
head = y; //reassign head to be actual new head of queue (y)
}
else{ //if there is already a tail node
tail.next = y; //assign the tail's pointer to the new node
tail = y; //reassign tail to actual new tail of queue (y)
}
n++; //increment the queue's size
}
//delete the minimim (highest priority value) from the queue
public Node deleteMin(){
if (n == 0){ //if the list is of size 0, and thus empty
return null; //do nothing
}
else{ //if there are node(s) in the list
Node min = head; //assign min to the head
head = head.next; //reassign head as next node,
n--; //decrement list size
return min; //return the minimum/highest priority value
}
}
//return the size of the queue
public int size() {
return n;
}
}
测试人员代码:
import work.Node;
import work.SLList;
import work.PriorityQueue;
public class Test {
public static void main(String[] args){
PriorityQueue PQueue1 = new PriorityQueue();
PQueue1.add(3);
PQueue1.add(2);
PQueue1.add(8);
PQueue1.add(4);
System.out.println("Test add(x): " + PQueue1);
System.out.println("Test size() " + PQueue1.size());
PriorityQueue PQueue2 = new PriorityQueue();
PQueue2 = PQueue1.deleteMin(); //the data types don't line up but I don't know what should be changed
System.out.println("Test deleteMin() " + PQueue2);
System.out.println("Test size() " + PQueue2.size());
}
}
答案 0 :(得分:1)
您的测试类的代码
PQueue2 = PQueue1.deleteMin(); //this line isn't working*
由于类型不匹配,此行无效:您无法从Node转换为PriorityQueue。
ClassCastException
的API规范:
抛出以指示代码已尝试将对象强制转换为不是实例的子类。例如,以下代码生成ClassCastException:
在您的示例中,这将起作用;
Node node = PQueue1.deleteMin(); //this will work