Insert with "for" in a linked list

0

I'm having a question, the teacher asked me to insert elements in the linked list using "for" but I'm having difficulty, the class that creates the node is working perfectly and the part that I was able to develop was that nullPointException when I try to insert from the second element onwards.

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 ++;
}
    
asked by anonymous 26.07.2017 / 19:22

1 answer

0

The problem is even with for itself. He should have another start instruction as well as another end instruction. 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 usually run until you get the end of the list, null . Even with a constraint of using 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 start to navigate in inicio , and we navigate until the next one is null , which is the case of stopping. When the next one is null it means that we are in the last element that is where we want to stop. For each navigation we will walk to the next element with aux = aux.getProximo(); as already done previously.

    
26.07.2017 / 19:44