1

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

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

假设 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->next ,正在被执行。

建议?

4

1 回答 1

2

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

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

void addNode(node*& root)

或指向指针的指针:

void addNode(node **root)
于 2012-04-22T22:25:45.287 回答