3
I am doing a job that I need to create a chained list and order it in ascending order, performing my tests I realized that I am losing the reference to a node, the problem may be logical but I am not able to find my mistake.
method to add and sort:
public void adiciona(Nodo novoNodo) {
for (Nodo i = primeiroNodoDistancia; i != null; i = i
.getProximoNodoDistancia()) {
if (i.getDistancia() > novoNodo.getDistancia()) {
novoNodo.setProximoNodoDistancia(i);
if (i.getNodoAnteriorDistancia() != null) {
novoNodo.setNodoAnteriorDistancia(i
.getNodoAnteriorDistancia());
i.getNodoAnteriorDistancia().setProximoNodoDistancia(
novoNodo);
i.setNodoAnteriorDistancia(novoNodo);
} else {
i.setNodoAnteriorDistancia(novoNodo);
}
if (i == primeiroNodoDistancia)
primeiroNodoDistancia = novoNodo;
}
if (novoNodo.getDistancia() > i.getDistancia()) {
novoNodo.setNodoAnteriorDistancia(i);
if (i.getProximoNodoDistancia() != null) {
novoNodo.setProximoNodoDistancia(i
.getProximoNodoDistancia());
i.getProximoNodoDistancia().setNodoAnteriorDistancia(
novoNodo);
}
i.setProximoNodoDistancia(novoNodo);
}
}
}
My test code looks like this:
c.adicionar(pedro, 50);
System.out.println(c.imprimirListaDistancia());
c.adicionar(joao, 20);
System.out.println(c.imprimirListaDistancia());
c.adicionar(maria, 10);
System.out.println(c.imprimirListaDistancia());
Departure from the Terminal:
Pedro
Joao Pedro
Maria Pedro
I’m missing the reference to the Joao that should be in the middle of the list..
You could post all your code, including the Nodo class. A tip: Java has a double-chained List implementations, Linkedlist is one of them, there are others, see the java.util interface.
– Filipe Miranda
Hello Filipe I can’t use any existing Java implementation. I did not post the class Nodo because it is very specific to the problem as a whole, the ordering is only one of them..
– Emanoel