Data Structure - Double C-Linked List

5

I am doing an activity proposed by a teacher, which asks you to remove an element from the end of a double chained list. But the function I put together to solve the problem is locking the program. In the resolution I thought that if it were made similar to a simple threaded list would solve.

Follow the code:

int Remover_fim_LD (Tno_ld **inicio){

    Tno_ld *aux, *percorre;

    if(*inicio == NULL)
    {
        printf("\n Lista vazia! \nRemocao impossivel\n");
        return 1;
    }

    else
    {
        percorre = *inicio;         
        while(percorre -> prox != NULL)
        {
            aux = percorre;
            percorre = percorre -> prox;                    
        }

        (percorre -> ant) -> prox = percorre -> prox;
        (percorre -> prox) -> ant = percorre -> ant;
        percorre -> prox = NULL;
        free(percorre);
    }
}
    
asked by anonymous 13.01.2015 / 13:01

2 answers

7

I did not realize it is because you do not use aux (penultimate) which is percorre->ant , which in turn will be the last one on the list.

while(percorre -> prox != NULL)
{
    aux = percorre;
    percorre = percorre -> prox;                    
}

free(aux->prox); // ou free(percorre);
aux->prox = NULL;

Free the last (aux->prox) and put the new last aux to point to NULL in the prox field.

    
13.01.2015 / 13:09
3

I'll try to explain it.

First, let's try to stay in the same point of understanding the code, when you exit the while, your aux variable will be pointing to the penultimate element in your list (which will become the last one after deletion of the last one), and you will be storing the pointer for the last element.

As you are saving the penultimate element, you just need to make aux-> prox = NULL; and give free in course, since you want to delete the last element and it is being pointed to by traverses, you only need to redo the pointing of the penultima element (aux) so that aux-> prox = NULL; (Making it the last element), as it runs it will be deleted, you do not need to redo your notes.

    
15.01.2015 / 02:00