Reputation: 16469
I created a method to insert a Linked List node in the correct place of a sorted (increasing) linked list but I am having some problems.
public static void sortedInsert(LinkedListNode root, int value) {
LinkedListNode newNode = new LinkedListNode(value);
if (root == null || root.data >= value) {
newNode.next = root;
} else {
LinkedListNode curr = root;
while (curr.next.data < value && curr.next != null) {
curr = curr.next;
}
newNode.next = curr.next;
curr.next = newNode;
}
}
errors:
Exception in thread "main" java.lang.NullPointerException
at LinkedLists.LinkedListProblems.sortedInsert(LinkedListProblems.java:188)
The curr.next != null
portion is highlighted in intellij so I'm assuming that is causing the error. This error only occurs when the value I added is bigger than the last value of the sorted linked list
However when the iterate to the last node of the linked list and the value of that node is still less than the value of the parameter. Shouldn't that exit the while loop?
Upvotes: 5
Views: 4067
Reputation: 5895
It looks like your first if should be != null, and it should be an &&, otherwise you can have root.data being evaluated even when root is null.
if (root != null && root.data >= value) {
Upvotes: 2
Reputation: 2576
You are getting an exception on that line because cur.next.data
gets tested before cur.next!=null
.
Swap them over and the &&
will be short circuited correctly avoiding the exception.
Upvotes: 2
Reputation: 201447
I think the problem is here
while (curr.next.data < value && curr.next != null) {
curr = curr.next;
}
You are testing in the wrong order, first check for null
-
while (curr.next != null && curr.next.data < value) {
curr = curr.next;
}
Otherwise when curr.next
is null
it will have already tested curr.next.data < value
which will throw a NullPointerException
.
Upvotes: 6