Problem to remove list element chained in C

3

My role is only removing the first element if I enter the name of this first element. I would like to know how I do for the function to find the element and remove it. The insert function is working so I will not put it .. Follow 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;
}
    
asked by anonymous 30.05.2015 / 20:29

2 answers

1

Assuming by your code that the list does not support elements with equal names ... I believe that 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.

    
23.08.2015 / 14:51
1
strcmp(name2, aux->nome);

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

    
23.06.2015 / 07:08