修改头指针在链表 [英] Modifying head pointer in a linked list
问题描述
我无法理解这种code。我真正需要的是修改头指针指向第一个元素。那么,为什么不*头工作?改变*头的变化值,其中该指针指向那应该工作,对不对?我已阅读通过引用传递/按值传递,但我觉得很难理解。有人可以帮助澄清这一点?
鸭preciate你的帮助。谢谢你。
在C / C ++更容易使具有指针滥用的错误。考虑这个C / C ++ code在列表的前面插入一个元素:
布尔insertInFront(IntElement *头,int数据){
IntElement * newElem =新IntElement;
如果(newElem!)返回false; newElem->数据=数据;
头= newElem; //不正确的!
返回true;
}
在preceding code不正确,因为它仅更新头指针的本地副本。正确的版本在传递一个指向头指针:
布尔insertInFront(IntElement **头,int数据){
IntElement * newElem =新IntElement;
如果(newElem!)返回false; newElen->数据=数据;
*头= newElem; //正确更新头
返回true;
}
您需要帮助理解的区别吧?
想象的功能在第一种情况下来电:
IntElement *头;
int数据;
...
insertInFront(头,数据);
现在,在这种情况下,该地址指向的头部被放置在栈上,并通过在作为参数insertInFront。当insertInFront做头=为newElement;只(在堆栈)参数被修改。
在第二种情况下,主叫方将是:
IntElement *头;
int数据;
...
insertInFront(安培;头,数据);
在这种情况下,头部的地址放置在堆栈上,并通过在作为参数传递给insertInFront。当你做*头=为newElement,这在转交地址被取消引用来获得原始表头的地址,而被修改。
I am having trouble understanding this code. All I really need is to modify the head pointer to point to the first element. So why won't *head work ? Changing the value of *head changes where this pointer points to and that should work, right ? I have read the pass by reference/pass by value, but am finding it hard to understand. Can someone help clarify this ? Appreciate your help. Thanks.
In C/C++ it’s easier to make mistakes with pointer misuse. Consider this C/C++ code for inserting an element at the front of a list:
bool insertInFront( IntElement *head, int data ){
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElem->data = data;
head = newElem; // Incorrect!
return true;
}
The preceding code is incorrect because it only updates the local copy of the head pointer. The correct version passes in a pointer to the head pointer:
bool insertInFront( IntElement **head, int data ){
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElen->data = data;
*head = newElem; // Correctly updates head
return true;
}
You need help understanding the difference right?
Imagine the caller of the function in the first case:
IntElement *head;
int data;
...
insertInFront (head, data);
Now, in this case, the address pointed to by head is placed on the stack and passed in as an argument to insertInFront. When insertInFront does head = newElement; only the argument (on the stack) is modified.
In the second case, the caller would be:
IntElement *head;
int data;
...
insertInFront (&head, data);
In this case, the address of head is placed on the stack and passed in as an argument to insertInFront. When you do *head = newElement, this passed in address is de-referenced to get the address of the original list head, and that is modified.
这篇关于修改头指针在链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!