How can I add elements into a linked list alphabetically?
I'm trying to add nodes of a Car
object into a linked list, but instead of sorting the input and then creating the list, I want to insert the inputs to the correct spot while they are being taken.
I've tried this using this method but there's a very strange bug that I am unable to resolve.
Here's my Car class with the compareTo
method I'm using for this:
public class Car implements Comparable<Car>{
String ID;
int regYear;
public Car(String id, int reg){
ID = id;
regYear = reg;
}
public int compareTo(Car c2){
return ID.compareTo(c2.ID);
}
public String toString(){
return "ID: " + ID + ", Reg Year" + regYear;
}
}
Here's the linked list class:
public class MyLinkedList {
Node start;
public void add(Car c) {
Node node = new Node(c);
if (start == null) {
start = node;
} else {
Node n = start;
while (c.compareTo(n.data) < 0) {
n = n.next;
}
n.next = node;
}
}
Now if I add two unsorted elements, let's say one with ID B
first and one with ID A
second, I get this:
Exception in thread "main" java.lang.NullPointerException: Cannot read field "data" because "n" is null referring to the n.data in the while loop.
If I add two already sorted elements, ID A
first and ID B
second, everything's just fine.
If I add elements A C B D
, it only adds A
and D
to the list and ignores C
and B
since they are unsorted.
What am I missing?
Solution 1:
you need a Null check at
while (c.compareTo(n.data) < 0) {
n = n.next;
}
This must be
while (n != null && c.compareTo(n.data) < 0) {
n = n.next;
}
This would still fail at the next line, as the handling is missing. In case you hit the end of list, you need to figure out where to insert the new node, after creating it.