Data Structure - C Double Chained List

Asked

Viewed 518 times

5

I’m doing an activity proposed by a teacher, who asks to remove an element from the end of a double chained list. Except the function I set up to solve the problem is locking the program. In the resolution I thought that if made similar to a simple chained list would solve.

Follows 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);
    }
}

2 answers

7

I don’t understand why you don’t use the aux (penultimate) which is the percorre->ant, which in turn will be the new last on the list.

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

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

You free the last (aux->prox) and put the new last aux pointing to NULL in the Prox field.

3

I will try to explain didactically.

First let’s try to stay at the same point of understanding of the code, when you exit while, your aux variable will be pointing to the penultimate element of your list(Which will become the last after the exclusion of the last) and traverses will be storing the pointer to the last element.

As you are saving the penultimate element, just do aux->Prox = NULL; and give free in traverse, since you want to delete the last element and it is being pointed by trave, you only need to redo the penultimate element(aux) to aux->Prox = NULL; (Making it the last element), as traverses will be excluded, you do not need to redo your notes.

Browser other questions tagged

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