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
.
看起来你的第一个应该是!= null,它应该是&&,否则即使root为null也可以对root.data进行求值。
if (root != null && root.data >= value) {
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.