Hello I am trying to implement a Priority Queue in Java from scratch with a linked list but I am having a problem sorting elements on insertion. Here is my program thus far, any help would be massively appreciated.
import java.util.Scanner;
public class T0 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
PQ myList = new PQ();
myList.addSort("Z");
myList.addSort("B");
myList.addSort("C");
myList.addSort("B");
myList.addSort("Z");
System.out.println(myList.view(0));
System.out.println(myList.view(1));
System.out.println(myList.view(2));
System.out.println(myList.view(3));
System.out.println(myList.view(4));
}
}
class PQ {
Node tail = new Node(null, null);
int elementCount = 0;
Node lastAdded = tail;
public void add(String word) {
Node added = new Node(word, lastAdded);
lastAdded=added;
elementCount++;
}
public void addSort(String word){
Node temp = new Node(null, null);
for(int n = 0; n<elementCount && word.compareTo(lastAdded.next().toString()) >1; n++){
temp=lastAdded.next();
}
Node added = new Node(word, lastAdded.next());
lastAdded.changeNext(added);
elementCount++;
}
public String view(int i){
Node temp = lastAdded;
for(int n = elementCount; n > i; n--){
temp=temp.next();
}
return temp.toString();
}
public String toString() {
return lastAdded.toString();
}
class Node {
String name;
Node nextNode;
public Node(String s, Node n) {
name = s;
nextNode = n;
}
public void changeNext(Node n){
nextNode=n;
}
public Node next() {
return nextNode;
}
public String toString() {
return name;
}
}
}
Currently outputs:
run:
Z
B
C
B
Z
BUILD SUCCESSFUL (total time: 1 second)
Upadate: Changed addSort to be:
public void addSort(String word){
Node temp = lastAdded;
for(int n = 0; n<elementCount && word.compareTo(lastAdded.next().toString()) > 0; n++){
temp=lastAdded.next();
}
Node added = new Node(word, lastAdded.next());
lastAdded.changeNext(added);
elementCount++;
lastAdded=temp;
}
This throws a null pointer exception at
System.out.println(myList.view(0));