Insertion at the end of a chained list C

Asked

Viewed 992 times

1

I would like to know how to go through the list so that I can add a new No at the end of it, in the case at the position no->Prox of the last in the present in the list. Here is my code:

typedef struct lista {
   struct no *prim;
} Lista;

typedef struct no {
   char *nome;
   char *apelido;
   char *email;
   struct no *prox;
} No;

void adicionar(Lista* lista, No var){
   No* novo = malloc(sizeof(No));

   novo->nome = var.nome;
   novo->apelido=var.apelido;
   novo->email=var.email;

   if (lista->prim == NULL){
      lista->prim = novo;
   }
   else{

   }
}

My doubt is about what to put in this This is so that this insertion is made.

1 answer

1


You only need to use one while to pass us until we reach the last. The last is the one that has the ->prox to NULL.

Thus:

...
else{
    No* atual = Lista->prim; //começar no primeiro
    while (atual->prox != NULL){ //navegar até ao fim
        atual = atual->prox;
    }

    atual->prox = novo; //colocar o novo nó no fim
}

Now this will only work if each time you create a new node to put at the end, or as a first node, you set up your ->prox correctly, specifying NULL, which is something you’re not doing.

So when creating the node you should add:

No* novo = malloc(sizeof(No));
novo->prox = NULL; //<--isto
  • Ahh, I get it now, I wasn’t initiating the new->Prox as NULL, so I was giving runtime error. Thanks.

Browser other questions tagged

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