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

  add, c++, linked-list, loops, pointers
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.

Source: Windows Questions C++

LEAVE A COMMENT