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

2

I need to add an element at the end of a linked list, I made the method asking it to add as if it were an initial element if the list is empty (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 in 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 from the file in repl.it whose problem is in LinkedList.cpp

link

(ignore link title)

    
asked by anonymous 24.04.2018 / 17:44

1 answer

2

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

You should create a new item and point the last one to the list, 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); 
}
    
24.04.2018 / 20:30