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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With