Remove first element from a simple chained list

0

I would like to do a function to remove the first element from a linked list, the way I did it 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: I have solved 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--;}
    
asked by anonymous 12.10.2017 / 09:13

2 answers

2
___ erkimt ___ Remove first element from a simple chained list ______ qstntxt ___

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

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

Edit: I have solved this algorithm.

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

When you pass by reference, you do not need to return the list.

%pre%     
______ azszpr245775 ___

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

%pre%     
___
12.10.2017 / 10:38
0

You can use the logical type (boolean) of the stdbool.h library to return true if the removal succeeded. And the code becomes 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; 
}
    
13.10.2017 / 14:37