Search code examples
c++loopspointerslinked-listaddition

Linked List creating a new pointer to add value but not working


void List::add_item(double new_value)
{
    if (list == nullptr)
    {
        list = new ValueList;
        list->value = new_value;
        list->next = nullptr;
    }
    else
    {
        ValueList* track = list;
        while (track != nullptr)
        {
            track = track->next;
        }
        track = new ValueList;
        track->value = new_value;
        track->next = nullptr;
    }
    size += 1;
}

With the following code above I'm trying to add a new value into the linked list by looping through the linked list until it reaches the end of the list and then create a dynamic variable to store that value in the linked list.

However I don't understand why it is not doing so when I output the linked list. It is only showing the last item in the list. Does this mean that track is actually pointing to list and when I loop through such as track = track->next, then list also changes? Which doesn't make sense to me at all.


Solution

  • Because you are passing by the last element. You should in reality check if next element is nullptr, not if the element you are on is nullptr.

    while (track != nullptr)
    {
       track = track->next;
    }
    

    should be:

    while (track->next != nullptr)
    {
       track = track->next;
    }
    
    track->next = new ValueList;
    track->next->value = new_value;
    track->next->next = nullptr;