How to add an element at the end of a linked list

Asked

Viewed 374 times

2

I need to add an element at the end of a linked list, I did the method asking it to add as if it were an initial element if the list is empty (it is working) and, if it is not, scrolling through the list as follows:

else{
    Celula * cursor = prim;
    while (cursor != NULL){
      cursor = cursor -> getProx();

For me, when it arrives at the stop condition, it is because the cursor = NULL, creating another condition to add the element that would be the following:

if (cursor == NULL){
  Celula * c = new Celula(i);
  c->setProx(prim);
  cout << cursor->getInfo()<< endl;

When I run the program, I can insert the first element normally, but when I insert it at the end, the program breaks.

If someone needs the full program to understand better (sorry if I’m not good with rs words), follow the link of the file in repl.it whose problem is in Liston.cpp

https://repl.it/@RodrigoCosta1/beijonabocaecoisadopassadoagramodaefazerlistaligada

(ignore the link title)

  • If it stops in NULL in making -> anything about NULL crash. Change the condition of the while for while (cursor->getProx() != NULL){

  • I switched and he didn’t crash, but he’s still not adding anything from the end.

  • This already has to do with the defining the next part. Looking at your code and without testing it would be something like following the while, do Celula * c = new Celula(i);c->setProx(NULL);cursor->setProx(c);

1 answer

2


You are not adding the items in the end, you are pointing all the new items to the first.

You should create a new item and point the last of the list to it, like this:

while (cursor->getProx() != NULL)
    cursor = cursor->getProx();

if (cursor->getProx() == NULL)
{
    Celula * c = new Celula(i);

    //  Aponta o ultimo item encontrado para o novo item.
    cursor->setProx(c); 
}

Browser other questions tagged

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