witcheR
witcheR

Reputation: 99

java - sorted list recursive insert method

I'm implementing an abstract class, and implementing an insert method which inserts into a sorted list. This is the recursive method I have so far:

public void insert(E data) {
    Node<E> temp = head;
    insert(temp, data);
}

private void insert(Node<E> curr, E data){
    Node<E> temp = new Node<E>(data);
    if (head == null || data.compareTo(head.data) < 0) {
        temp.next = head;
        head = temp;
    }
    else if(curr.data.compareTo(data) < 0 && (curr.next == null || curr.next.data.compareTo(data) > 0)){
        temp.next = curr.next;
        curr.next = temp;
        return;
    }
    else{
      insert(curr.next, data);
    }
}

However, anytime I try to insert 2+ items into the list, I get a null pointer exception error. Can someone explain my mistake? This is what happens when I try to run it simply inserting 1 and 2: https://gyazo.com/d254d563675b9d1b0efbce443eda4445

Upvotes: 0

Views: 1118

Answers (1)

merterpam
merterpam

Reputation: 785

It says that there is a NullPointerException at line 53, which is the else-if statement:

else if(curr.data.compareTo(data) < 0 && curr.next.data.compareTo(data) > 0)

I think it gives that exception because curr.next is null. From the way I can see, when you add the first element you initialize head, but head.next is null (temp.next = head is null as head is null at that time). So when you try to add the second element, you are unable to access curr.next.data and it gives NullPointerException.

Upvotes: 1

Related Questions