remove a specific item from a chained list in c

Asked

Viewed 2,416 times

0

have the

    struct LDISP
{
int  idAviao;
struct LDISP *prox;
};
typedef struct LDISP ldisp;

I already have the process of adding I would like to know how I can remove from a list an item whose int is equal to idaviao

  • Remember that removing the first item from the list has extra complications.

  • What have you tried to do? Do you at least know how to find the item that will be removed? Edit the question to add this kind of detail.

1 answer

1


To remove an item from the list, you first need to check if it is 0 or if it is N.

When position is 0, you have to go through the value with its original list.

When position is n, can use an auxiliary variable to help.

int remove_item(ldisp **l, int id){
    if(!(*l)) // encerra se não houver item na lista
        return 0;

    ldisp *aux = (*l);
    if((*l)->idAviao == id){ // verifica se posição == 0
        (*l) = (*l)->prox; // coloca a lista no próximo item
        free(aux); // limpa a memória

        return 1; // finaliza com verdadeiro
    }

    ldisp *prev;
    while(aux){ // verifica se aux não chegou ao fim e percorre a posição
        prev = aux; // prev guarda valor da remoção
        aux = aux->prox;
        if(aux && aux->idAviao == id){ // verifica o id do avião
            prev->prox = aux->prox;
            free(aux);
            return 1;
        }
    }
    return 0;
}
  • sorry for the ignorance but what would be the **l with only one asteeriso and the pointer, which parameter should pass in this case?

  • that code removes position n from the list what I want and remove when the content is equal to the number of the most obliged plane anyway

  • the *l serves to take the value from inside the memory address of l, when working with pointers, you must use it this way otherwise you cannot remove the item.

  • @user2296455 I changed the code to remove by the plane id, from to realize that both are equal, only changes the check

  • **l is a pointer of a pointer. l has a pointer to another variable. **l is the variable pointer.

  • thank you worked

  • if the code was solved your problem, you can click the v next to the answers to indicate that your question has been solved

Show 2 more comments

Browser other questions tagged

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