I’m trying to build a lexicographically ordered linked list. I planned it all out on paper and thought I need everything right, but once I insert a second or third entry it returns with a null pointer exception.
Exception in thread "main" java.lang.NullPointerException
at DoublyLL.insert(DoublyLL.java:88)
If I enter, for examples:
"chris", "andy", then "bob", "bob" returns the excpetion.
"chris", "bob", then "andy", "andy" returns the exception
"andy", "bob", I get the same exception with the addition of at DoublyLL$Node.access$000(DoublyLL.java:148)
The code:
public boolean insert(StudentListing newListing)
{ Node n = new Node();
if(n == null) // out of memory
return false;
else
{
Node q = new Node();
q = h;
int lex;
if (q.next == null) // first inputed node
{
n.next = q.next;
q.next = n;
n.back = q;
n.l = newListing.deepCopy();
return true;
} else // not first node
{
q = q.next;
do
{
// This is the line the error is called vvv
lex = q.l.getKey().compareTo(newListing.getKey());
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
if (lex < 0)
{
// keep going
q = q.next;
} else if (lex > 0)
{
// place before q
n.back = q.back;
q.back = n;
n.next = q;
n.back.next = n;
return true;
} else if (lex == 0)
{
// q and listing match
}
} while (lex < 0);
}
}
return false;
}
Inner class
public class Node
{ private StudentListing l;
private Node next;
private Node back;
public Node()
{ }
}
The biggest problem here is that, when you’re inserting a new
StudentListingto a non-empty list, you iterate over the list until you find an element that’s greater than theStudentListingyou’re inserting. But if theStudentListingthat you’re inserting is greater than any element in the list, then you never find such an element, so you run off the end of the list. Before writingq = q.next, you need to check ifq.next == null, and handle that case appropriately.(There are also various little non-Java-isms in your code — for example,
if(n == null) // out of memorywill never be true, because Java indicates an out-of-memory error by raising an exception rather than by returningnull— but none of those looks like a major problem to me.)