我无法理解这段代码。我真正需要的只是修改头指针以指向第一个元素。那么为什么 *head 不工作呢?更改 *head 的值会更改此指针指向的位置,这应该有效,对吧?我已经阅读了按引用传递/按值传递,但发现很难理解。有人可以帮助澄清这一点吗? 感谢你的帮助。谢谢。
在 C/C++ 中,指针误用更容易出错。考虑用于在列表前面插入元素的 C/C++ 代码:
bool insertInFront( IntElement *head, int data ){
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElem->data = data;
head = newElem; // Incorrect!
return true;
}
前面的代码是不正确的,因为它只更新了头指针的本地副本。正确的版本传入一个指向头指针的指针:
bool insertInFront( IntElement **head, int data ){
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElen->data = data;
*head = newElem; // Correctly updates head
return true;
}
最佳答案
您需要帮助了解其中的区别,对吗?
想象一下第一种情况下函数的调用者:
IntElement *head;
int data;
...
insertInFront (head, data);
现在,在这种情况下,head 指向的地址被放在堆栈上并作为参数传递给 insertInFront。当 insertInFront 执行 head = newElement;只有参数(在堆栈上)被修改。
在第二种情况下,调用者将是:
IntElement *head;
int data;
...
insertInFront (&head, data);
在这种情况下,head 的地址被放在堆栈上并作为参数传递给 insertInFront。当您执行 *head = newElement 时,这个传入的地址将被取消引用以获取原始列表头的地址,并进行修改。
关于c - 修改链表中的头指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6810359/