Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition always true when reached in while loop

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?

like image 605
Liondancer Avatar asked Jul 29 '14 05:07

Liondancer


1 Answers

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.

like image 169
Elliott Frisch Avatar answered Oct 09 '22 14:10

Elliott Frisch