Reputation: 634
Trying to figure out how to sort my doubly linked list. I get a null pointer exception here:
while (temp.getNext()!=null){
Is there a better approach or any advice to get this going the right way?
public void sort() {
//bubble sort!
boolean swapped = (head != null);
while (swapped) {
swapped = false;
EntryNode temp = head;
//can't swap something with nothing
while (temp.getNext()!=null){
if (temp.getLastName().compareTo(temp.getNext().getLastName()) > 0) {
swapped = true;
//special case for two nodes
if (size == 2) {
//reassign head and tail
tail = temp;
head = temp.getNext();
tail.setPrev(head);
head.setNext(tail);
tail.setNext(null);
head.setNext(null);
}
//if swapping is at head
else {
if (temp == head) {
head = temp.getNext();
temp.setNext(head.getNext());
head.getNext().setPrev(temp);
head.setPrev(null);
head.setNext(temp);
temp.setPrev(head);
}
else {
temp.setNext(temp.getNext().getNext());
temp.setPrev(temp.getNext());
temp.getNext().setNext(temp);
temp.getNext().setPrev(temp.getPrev());
}
}
}
//loop through list
temp = temp.getNext();
}
}
}
Upvotes: 3
Views: 6057
Reputation: 236124
Use the merge sort algorithm, is often the best choice for sorting a (single or doubly) linked list. There's already a post discussing the relevant implementation issues.
Upvotes: 2
Reputation: 719336
The simple approach is to put the list contents into an array, use Arrays.sort
to sort the array, and finally rebuild the list from the sorted array.
Upvotes: 0
Reputation: 1765
I think you should check for:
while(temp != null)
because you are already assigning
temp = temp.getNext()
at the end of the while
loop.
Upvotes: 1