I am trying to create a sorted linked list that sorts as new numbers are added in Java. The way I would like the program to work is to insert the new node in the correct place so that it is sorted. However, I keep getting a NullPointerException. Here is my code:
public void Add(int d){
Node newNode = new Node(d);
if(first == null){
first = newNode;
return;
}
Node cur = first.next;
Node prev = first;
if(newNode.data > prev.data){
newNode.next = first.next;
first = newNode;
return;
}
while(cur.next != null){
if(cur.data < newNode.data && prev.data > newNode.data){
newNode.next = cur;
prev.next = newNode;
}
cur = cur.next;
prev = prev.next;
}
cur.next = newNode;
}
I have no idea why it does not work.