Method malfunction Remove at position defined in Dynamic List

Asked

Viewed 76 times

0

The following method performs a removal of an element at a pre-defined position in the test class but appears not to be working even if there are no syntax errors and errors in the teacher’s test.

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 exit :

72 2 16 74

Expected exit :

 72 2 16 74
 72 16 74 
 72 74
 72

(always removing the element that is in position 1)

  • "It appears not to be working". Why?

  • remove at start : 28 60 90 89 / 60 90 89 / 90 89 / 89 remove at end : 14 11 48 5 / 14 11 48 / 14 11 / 14 remove at position 1 : 72 2 16 74. This is what appears in the terminal of the tests of the 3 methods.

  • he would have to gradually decrease the list equal to the other 2 methods by removing only the element q would be at position 1 ? remove at position 1 : 72 2 16 74 / 72 16 74 / 72 74 / 72.

  • You can post your complete code so that it is compilable?

1 answer

0


Difficult without seeing the full code, but by logic the following line is wrong:

ant.setProximo(null);

because it not only erases the desired position, but also the rest of the list. In that 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 docked, the above line should be:

ant.setProximo(aux.getProximo());

that is, the element before the one being deleted (ant) should point to the next element to the element being deleted.

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

Browser other questions tagged

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