Malfunction of the Remove method in the defined position in the Pivot List

0

The following method performs a removal of an element at a pre-defined position in the test class but does not appear to be working even though it has no syntax errors and errors in the test done by the teacher.

public void removerPosicao(int posicao){
    try {
        if(posicao == 0){
             removerPrimeiro();
        }else if(posicao == (getTamanho()-1)){
            removerUltimo();
        }else{
            Node aux = inicio;
            Node ant = aux;
            int posicao_atual = 0;
            while(posicao > posicao_atual){
                ant = aux;
                aux = aux.getProximo();
                posicao_atual++;
            }
            ant.setProximo(null);
            tamanho--;
        }    
    } catch (Exception e){
            System.out.println("Erro:" + e + ". Inserir posicao valida !");
    }
}


@Test
public void testarRemoverPosicao(){
    iniciarLista();
    for(int i = 0; i < 3; i++){        
        lista.removerPosicao(1);
        System.out.println(lista.toString());
    }
}

Terminal output:

72 2 16 74

Expected output:

 72 2 16 74
 72 16 74 
 72 74
 72

(always removing the element that is in position 1)

    
asked by anonymous 15.08.2017 / 23:09

1 answer

0

Difficult to see the complete code, but by logic the following line is wrong:

ant.setProximo(null);

because it not only deletes the desired position, but also the rest of the list. In this case the output should be (and this should be in the question):

72 2 16 74
72
72
72

To delete an element from a list simply link, the above line should be:

ant.setProximo(aux.getProximo());

That is, the previous element to the one being deleted ( ant ) should point to the next element to the element being deleted.

(assuming it is a list that is simply chained, and the rest of the code is doing what the names suggest.) example: removerUltimo() removes the last element, setProximo() arrow the next node, ... )

    
16.08.2017 / 12:05