在C ++中将指针传递给链表

时间:2012-04-22 22:19:37

标签: linked-list

我有一个相当基本的程序,旨在通过链接列表对数字列表进行排序。

我挂断的地方是需要在列表的开头插入元素的时候。这是有问题的代码块

假设root-> x = 15并假设用户在提示时输入12:

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
}

但是,如果在运行此功能后,我尝试

cout << root->x;

回到main(),再次显示15。所以代码

root=temp;
离开功能后,

正在丢失。现在对* root的其他更改,例如向LL添加另一个元素并在其旁边指向root-&gt;,正在继续进行。

建议?

1 个答案:

答案 0 :(得分:2)

这是因为您正在设置本地node *root变量,您不是修改原始根,而只是修改堆栈上传递的参数。

要修复它,您需要使用对指针的引用,例如:

void addNode(node*& root)

或指向指针的指针:

void addNode(node **root)