Question

I am writing a program that performs functions on a singly linked list containing nodes of the following structure:

typedef int ITEM;
typedef struct NODE* NODEptr;

struct NODE
{
    ITEM data;
    NODEptr next;
};

And this is the function I call to add a node to the head of the list (hdList points to the head of the list):

void addToHead(NODEptr &hdList, ITEM input)
{
    NODEptr newNode = new NODE; 
    newNode->data = input;
    newNode->next = nullptr;
    hdList = newNode; 
}

However I found whilst using the debugger that the value of hdList is not updated when the program leaves the function, even though it is being passed by reference, and I am not sure why.

Many thanks for your help and advice.

EDIT: As requested, full code here: http://pastebin.com/bLv0S2QG Also I am compiling with Visual Studio 2013

Was it helpful?

Solution

The correct function will look as

void addToHead(NODEptr &hdList, ITEM input)
{
    NODEptr newNode = new NODE; 
    newNode->data = input;
    newNode->next = hdList;
    hdList = newNode; 
}

Or if your compiler supports the C++ 2011 then

void addToHead(NODEptr &hdList, ITEM input)
{
    NODEptr newNode = new NODE { input, hdList }; 
    hdList = newNode; 
}

Initially hdList has to be initialized by nullptr or NULL. For example

NODEptr hdList = nullptr;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top