Sorting method for double list of links

Trying to figure out how to sort my doubly linked list. Here's where I get a null pointer exception:

while (temp.getNext()!=null){

      

Is there a better approach or advice to get things right?

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();
        }
    }
}

      

+3


source to share


3 answers


Use the merge sort algorithm , often the best choice for sorting (one or two) linked lists. There is already a post there discussing the related implementation issues.



+2


source


I think you should check:

while(temp != null)

      

since you are already assigning



temp = temp.getNext()

      

at the end of the cycle while

.

+1


source


A simple approach is to put the contents of the list into an array, use Arrays.sort

to sort the array, and finally rebuild the list from the sorted array.

0


source







All Articles