Passing a pointer to a linked list in C++

走远了吗. 提交于 2020-01-14 04:14:14

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/10272626/passing-a-pointer-to-a-linked-list-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!