1

I have a fairly basic program that is intended to sort a list of numbers via a Linked List.

Where I am getting hung up is when the element needs to be inserted at the beginning of the list. Here is the chunk of code in question

Assume that root->x = 15 and assume that the user inputs 12 when prompted:

void addNode(node *root)
{
int check = 0;  //To break the loop
node *current = root;   //Starts at the head of the linked list
node *temp = new node;


cout << "Enter a value for x" << endl;
cin >> temp->x;
cin.ignore(100,'\n');


if(temp->x < root->x)
{
    cout << "first" << endl;
    temp->next=root;
    root=temp;

        cout << root->x << " " << root->next->x; //Displays 12 15, the correct response
}

But if, after running this function, I try

cout << root->x;

Back in main(), it displays 15 again. So the code

root=temp;

is being lost once I leave the function. Now other changes to *root, such as adding another element to the LL and pointing root->next to it, are being carried over.

Suggestions?

Taylor Huston
  • 1,104
  • 3
  • 15
  • 31
  • Are you intending addNode to add a node to the front of the list, or to actually add the node to the sorted position? the intention is not clear. You should also read the value from outside the function and pass it in. – hookenz Apr 22 '12 at 22:28

1 Answers1

2

This because you are setting the local node *root variable, you are not modifying the original root but just the parameter passed on stack.

To fix it you need to use a reference to pointer, eg:

void addNode(node*& root)

or a pointer to pointer:

void addNode(node **root)
Jack
  • 131,802
  • 30
  • 241
  • 343
  • It's incomplete anyway. Where's the ending brace? – hookenz Apr 22 '12 at 22:28
  • Huzzah! I knew it was something simple @Matt H this isn't the complete program, just the part that was giving me trouble. After that code comes the part of inserting an element into the middle or end of the list, which was working fine. – Taylor Huston Apr 22 '12 at 22:30