我正在使用链接列表实现Java中的Priority Queue,设置优先级顺序,我试图将所有链接列表对象转移到数组进行排序,然后再次返回到Linked列表(优先排序后)。我尝试了这段代码,但我得到了#34;空指针异常"每次我将Linked List Object传递给Array。我该怎么办?
public class Node {
Node next;
Object data;
int pref;
Node() {
this(0, null);
}
Node(Object m, Node s) {
setData(m);
next = s;
}
Node(Object m, Node s, int pref) {
setData(m);
next = s;
this.pref = pref;
}
void setData(Object m) {
data = m;
}
public Object getData() {
return data;
}
public void setPref(int pref){
this.pref = pref;
}
public int getPref(){
return pref;
}
}
public class PriorityQueue(){
public Node head;
PriorityQueue(){
head = null;
}
public boolean enQueue(Object v, int p) {
Node newNode = new Node();
newNode.setData(v);
newNode.setPref(p);
if (head == null) {
newNode.next = head;
head = newNode;
return true;
} else {
Node current = head;
try {
while (current.next != null) {
current = current.next;
}
current.next = newNode;
settingPriorityLevel();
return true;
} catch (java.lang.OutOfMemoryError e) {
System.out.println(e.getMessage());
return false;
}
}
}
public void settingPriorityLevel(){
Node arr[] = null; //converting LinkedList to array for sorting purpose
Node current = head;
Node temp;
for(int i = 0; i <= size(); i++){
arr[i] = current;
current = current.next;
}
for(int i=0; i < arr.length; i++){ //sorting
for(int j = i+1; j < arr.length; j++){
if(arr[i].pref > arr[j].pref){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int i = 0; i < arr.length; i++){ //shifting back to LinkedList
current = arr[i];
current = current.next;
}
}
}