0

I am implementing a link list with cpp,what is wrong with the following code? Every time i step into the function---AddToTail, the "list" can't get correct value. It changes it value to the new constructed node.

#include <iostream>
using namespace std;

struct Node
{
    int value;
    Node * next;
};

void AddToTail(Node* &list, int value)
{
    Node  newnode;
    newnode.value = value;
    newnode.next = NULL;

    if (list == NULL)
        list = &newnode;
    else
    {
        Node * list1 = list;
        while (list1->next != NULL)
        {
            list1 = list1->next;
        }
        list1->next = &newnode;
        int a = 1;
    }
}
int main()
{
    Node *list=NULL;

    AddToTail(list, 1);
    AddToTail(list, 2);
    AddToTail(list, 3);

    while (list->next != NULL)
    {
        cout << list->value << endl;
        list = list->next;
    }
    system("pause");
}
YSC
  • 5
  • 1
  • 4
  • Refer this [question](https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap) to know the difference between stack and heap memory. – Ravi Chandra May 30 '17 at 05:38

1 Answers1

1
void AddToTail(Node* &list, int value)
{
    Node  newnode;
    // Set up fields of newnode.
    // Store address of newnode into some other data structure.
}

This is your issue. You are creating a node on the stack and this node will go out of scope at the end of the function. The reason it seems to be interfering with later node creations is because re-entering the function will almost certainly create newnode at exactly the same address as in the previous call.

If you want objects to survive function scope, you're going to need to allocate them dynamically, something like:

void AddToTail (Node *&list, int value) {
    Node *newnode = new Node();             // create on heap.
    newnode->value = value;                 // set up node.
    newnode->next = nullptr;

    if (list == nullptr) {                  // list empty,
        list = newnode;                     //   just create.
        return;
    }

    Node *lastNode = list;                  // find last item.
    while (lastNode->next != nullptr)
        lastNode = lastNode->next;
    lastNode->next = newnode;               // append to that.
}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953