Insert with "for" into a chained list

Asked

Viewed 216 times

0

I have a question, the teacher asked to insert elements in the chained list using the "for" but I’m having difficulty, the Class that creates the node is already working perfectly and the part that I was able to develop was this but this giving nullPointException when I try to insert from the second element on.

public void inserir(Node novoNode){
        if(inicio == null){
            inicio = novoNode;
        } else {
            Node aux = inicio;
            for(int i = tamanho ; i < (tamanho +1) ; i++){
                aux = aux.getProximo();
             }
            aux.setProximo(novoNode);
        }
        tamanho ++;
}
  • Who is "start"? How do you initialize the size? Who calls the insert method by passing the new?

1 answer

0


The problem is really in itself for. He should have another beginning instruction as well as another end instruction. In this way:

//de 0 até ao tamanho - 1 para parar no ultimo
for(int i = 0; i < tamanho - 1; i++){  
    aux = aux.getProximo();
}

List codes are usually written with while and they usually execute until they catch the end of the list, null. Even with a restriction of using one for we can use the same logic, which simplifies:

else {
    Node aux;

    //escrito desta maneira fica sem conteúdo, servindo so para navegar até ao ultimo
    for(aux = inicio; aux.getProximo() != null ; aux = aux.getProximo());

    aux.setProximo(novoNode);
}

In this last example we started to navigate the inicio, and sail until the next null, which is the case of stopping. When the next is null means that we are in the last element that is where we want to stop. For each navigation we are going to the next element with aux = aux.getProximo(); as was done before.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.