I have the following code that gives an error
class Nodo {
int info;
Nodo sig;
}
Nodo raiz;
public void insertar(int x) {
Nodo insertado = new Nodo();
insertado.info = x;
if (raiz == null) {
raiz = insertado;
return;
}
if (insertado.info > raiz.info) {
insertado.sig = raiz;
//raiz.ant = insertado;
raiz = insertado;
return;
}
Nodo reco = raiz;
Nodo recob = reco.sig;
while (recob.info > insertado.info && recob != null ) {
reco = reco.sig;
recob = recob.sig;
} //EN ESTE WHILE ESTÁ EL ERROR
what I don't understand is why the following block of code compiles fine:
public void mostrarElementos() {
Nodo reco ;
reco = raiz;
while (reco != null) {
System.out.println(reco.info);
reco = reco.sig;
}
if in both cases the while would be making a pointer (in the first case "recob" and in the second "reco") end up pointing to null.
Without having understood the whole problem, I can tell you that this is not right:
If recob were null (which you check in the second part of that
&&
) then you would have an NPE because you are trying to use a member of recob before you know if recob is null. This is because evaluations are done from left to right. you would have to placefor you to avoid the NPE.