링크 된 목록을 사용하여 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;
}
}
2 등석 :
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());
}
}
노드 유형의 값으로 PriorityQueue 유형의 참조를 지정하려는 경우, 하나의 클래스 계층 구조에서 이벤트가 발생하지 않습니다. –
"무언가가 작동하지 않습니다"명시하십시오. 작동하지 않는 것은 무엇입니까? – weston
모든 것을 주석하지 마십시오. 'Node head' - 예,리스트의 머리 부분입니다. 영어로 쓰지 않아도됩니다. 코멘트의 목적은 코드를 영어로 번역하는 것이 아닙니다. 작성한 내용의 추론이 무엇인지 설명하기 위해 주석을 사용해야합니다. size 변수를'int n'으로 선언하고 그 옆에 주석을 쓰는 대신,'int size'를 사용하십시오. 훨씬 더 깔끔하고 분명합니다. 왜 그런 일이 일어나고 있는지, 그리고 무슨 일이 일어나고 있는지를 설명함으로써 설명하십시오. – rafid059