Problem to remove chained list element in C

Asked

Viewed 12,386 times

3

My function is only removing the first element if I enter the name of that first element. I would like to know how I do for the function find the element and remove it. The insert function this working so I will not put it.. Follows the code:

typedef struct TLista
{
    struct TLista *prox;
    char nome[30];
    char end[40];
    int idade;
}TLista;

typedef TLista *PLista;

PLista inicializa()
{
    return NULL;
}
PLista remover(PLista p)
{
    PLista ant = NULL;
    PLista aux = p;
    char name[60], name2[60];
    getchar();
    strcpy(name2, aux->nome);
    strlwr(name2);
    printf("\nEntre com o nome que deseja remover: ");
    gets(name);
    strlwr(name);
    while(aux!=NULL && strcmp(name, name2) !=0)
    {
        ant = aux;
        aux = aux->prox;
    }
    if (aux == NULL || p == NULL)
    {
        return p;
    }
    else if(ant == NULL)
    {
        p = aux->prox;
    }
    else if(aux->prox == NULL)
    {
        ant->prox = NULL;
    }
    else
    {
        ant->prox = aux->prox;
    }
    printf("\n      Nome removido com sucesso!\n\n");
    free(aux);
    return p;
}

2 answers

1


Assuming by your code that the list does not admit elements with equal names... I believe this solution solves your problem.

Good studies =)

PLista remover(PLista p)
{
    //lista vazia
    if(p == NULL){
        return NULL;
    }

    char name[60], name2[60];
    printf("\nEntre com o nome que deseja remover: ");
    gets(name);
    strlwr(name);

    PLista ant = NULL;
    PLista aux = p;
    while(aux != NULL)
    {
        //como observou fabiano esta linha fica dentro do laco
        strcpy(name2, aux->nome);
        strlwr(name2);

        if(strcmp(name, name2) == 0)
            break;

        ant = aux;
        aux = aux->prox;
    }

    //se ant for null entao o elemento a ser removido é o primeiro ... esse caso precisa de tratamento especial
    if(ant == NULL){
        p = p->prox;
        printf("\n\tNome removido com sucesso!\n\n");
        free(aux);
    }
    //aux for diferente de NULL entao o while parou antes do fim da lista (Logo existe elemento com nome igual ao fornecido)
    else if(aux != NULL){
        ant = aux->prox; //ant agora aponta para o elemento que sucede aux
        printf("\n\tNome removido com sucesso!\n\n");
        free(aux);
    }

    return p;
}

It would be a good exercise to create a list with repeated names and remove all of them.

  • 2 months ago lol

1

strcmp(name2, aux->nome);

This line has to be inside the for, so that each node updates the name2 value if not you will always compare the name of the first element, hence the reason you were only able to delete the first.

Browser other questions tagged

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