Remove first element from a simple chained list

Asked

Viewed 1,339 times

1

I would like to do a function to remove the first element from a chained list, the way I did it is only removing the first node and removing the second element.

struct lista {
int info;
struct lista* prox;
};
typedef struct lista Lista;    

Lista* removeInicio(Lista *l){
if(l->prox == NULL){
    printf("Lista ja esta vazia\n");
    return NULL;
}else{
    Lista *tmp = l->prox;
    l->prox = tmp->prox;
    return tmp;
}

}

Edit: Solved with this algorithm.

Lista* removeInicio(Lista *l){
Lista* pointer = l->prox;
if(l->prox == NULL){
    printf("Lista ja vazia\n\n");
    return NULL;
}
l->prox = pointer-> prox;
free(pointer);
l->info--;}
  • The function it has gives perfectly to remove an element but it lacks the free and has to be called in the right way with minhaLista = removeInicio(minhaLista);. A more idiomatic solution in C is the response of Claudio Lopes passing the pointer address and not doing based on returns.

2 answers

3

When passing by reference, you do not need to return to the List.

void deletefirst (struct Lista **head) {
   struct Lista *tmp = *head;            
   if (tmp == NULL) return;             
   *head = tmp->next;                 
   free (tmp);                          
}

1

You can use the logical (boolean) type of the stdbool. h library to return true if the removal has worked. And the code is more understandable if you have the representation of a node.

typedef struct nodo {
    int info;
    struct nodo* prox;
}Nodo;

typedef struct lista {
    Nodo *primeiro; 
}Lista;    

bool removeInicio(Lista *lista){
   if(lista->primeiro == NULL){
      printf("Lista ja vazia\n\n");
      return false;
   }
   Nodo *removido = lista->primeiro;

   lista->primeiro = lista->primeiro-> prox;
   free(removido);
   return true; 
}

Browser other questions tagged

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