Pregunta

tratando de averiguar cómo ordenar mi lista doblemente vinculada. Obtengo una excepción de puntero nulo aquí:

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

¿Existe un mejor enfoque o algún consejo para obtener este camino correcto?

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

¿Fue útil?

Solución

Use la Combine el algoritmo , es a menudo el la mejor opción para clasificar una lista enlazada (sola o doblemente).Ya hay una POST discutiendo los problemas de implementación relevantes.

Otros consejos

Creo que deberías verificar:

while(temp != null)

porque ya estás asignando

temp = temp.getNext()

al final del bucle de while.

El enfoque simple es colocar los contenidos de la lista en una matriz, use Arrays.sort para ordenar la matriz, y finalmente reconstruir la lista de la matriz ordenada.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top