Removing cells at the beginning of a list

Asked

Viewed 100 times

3

I have this little problem of removing an element from the beginning of a list, even doing the schematic in the drawing I could not. The strange thing is that it works with up to 3 elements, from 4 cmd (which I’m using gcc to compile) to answer. Any idea?

    typedef struct evento_t {
    double tempo;
    char descricao[50];
    int id_origem, id_destino;
    struct evento_t *prox;
    } evento_t;

    void eventos_remover_inicio (evento_t **lista) {

    evento_t *auxiliar = *lista;

    if (*lista == NULL)
        printf ("Lista vazia\n");

    else 
        *lista = auxiliar->prox;

    free(auxiliar);

}
  • The only "wrong" thing I’m seeing is that after checking if the list is empty, you still let it be realized free in the empty list: free(auxiliar) => free(NULL) if *lista == NULL. Even so, if the environment follows the pattern, this should not generate side effects ("If ptr is NULL, no Operation is performed"). You need to show the code that declares and initializes a list and removes the elements.

3 answers

2

The only potential problem I see in this code is if you’re calling with something similar to this:

evento_t **lista;
lista = NULL;
eventos_remover_inicio(lista);

In this case the function will give problem because there is no pointer integrity test *lista before its use. If that’s your problem I’d recommend something like that:

void eventos_remover_inicio (evento_t **lista) {

    if(lista == NULL) 
    {
        return;
    }

    evento_t *auxiliar = *lista;

    if (*lista == NULL)
         printf ("Lista vazia\n");

    else 
         *lista = auxiliar->prox;

    free(auxiliar);
}

But it would be much easier to understand the problem if you post the code that uses this function and is giving problem.

1

I didn’t understand the need to use pointer to pointer in 'list'. What characterizes a list is the fact that its elements have pointers to elements of the same type; struct evento_t *list; list = malloc( sizeof( evento_t ), 1 );//or something similar, I forgot how to use malloc. list->Prox = malloc( sizeof( evento_t ), 1 );

  • Also, Voce checks the validity of the first pointer in if( list == NULL ); i.e., list can point to a pointer, and this can still be null.

0

Hello, Try to base yourself on this example.

typedef struct node{
    int value;
    struct node *next;
}Node;

// Como declarar o root da lista ligada
Node *root = NULL;

void removeFirstNode(Node *list){
    Node *aux = list;
    if(list == NULL){
        return NULL;
    }else{
        list = aux->next;
        free(aux);
    }
}

Browser other questions tagged

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