我想在java中使用鏈表創建一個優先級隊列,但是某些功能無法正常工作。我理解優先級隊列的一般功能,但在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());
}
}
想要將類型爲Priority的類型的引用賦值爲節點類型的值,它們在一個類層次結構中不是事件。 –
「有些東西不能正常工作」,請明確。什麼不起作用? – weston
不要評論一切。 '節點頭' - 是它是列表的頭。你不必用英文寫。評論的目的不是將代碼翻譯成英文。你應該用評論來解釋你寫的東西背後的推理。而不是聲明大小變量爲'int n'並在旁邊寫一個註釋,這樣做:'int size'。它更清晰明顯。通過解釋它爲什麼會發生,而不是發生了什麼的評論:) – rafid059