remove a specific item from a list chained in c [closed]

0

I have to

    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 an ldisp list an item whose int has equal idaviao

    
asked by anonymous 17.04.2016 / 20:44

1 answer

1

To remove an element from the list, you must first check if it is 0 or if it is N .

  

When position is 0 , you should go through the value with your original list.

     

When position is n , you 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;
}
    
17.04.2016 / 21:14