Brendon Brendon -4 years ago 78
Java Question

Trying to insert sort a linked list

I'm trying to Insert Sort random integers into the linked list from smallest to largest. Every time I run this method it will begin sorting and printing but will eventually give me a nullpointerexception? Any help is appreciated.

public void insertInOrder(int x) {
if (head == null) {

head = new Node(x);

} else {
Node prev;
Node curr;

for (prev = null, curr = head;
(curr != null) && (x > curr.getNumber());
prev = curr, curr = curr.getNext()) {}

if (prev == null) {
insertAtHead(x);
}

if (curr == null) {
insertAtTail(x);
} else {
Node nNex = new Node(x);
nNex.setNext(curr);
prev.setNext(nNex);
}
}
}

Answer Source

You should do an if, else if, and else statement instead of a double if and else:

This is what you have

if (prev == null) {
    insertAtHead(x);
}

if (curr == null) {
    insertAtTail(x);
} else {
    Node nNex = new Node(x);
    nNex.setNext(curr);
    prev.setNext(nNex);
}

You check if prev is null, If it is it goes in the first if statement, but if curr is null, when you enter the else statement prev is still null. You should do:

if (prev == null) {
    insertAtHead(x);
}

else if (curr == null) {
    insertAtTail(x);
} else {
    Node nNex = new Node(x);
    nNex.setNext(curr);
    prev.setNext(nNex);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download