我正在尝试温习我的 C 语言,并且一直在复习数据结构和指针操作。有人可以向我解释一下为什么在这个链表反向函数中需要使用指向 head 的指针吗?由于 head 在函数中总是被解引用一次 (*head),我们难道不能接受一个普通的 Node* 作为该函数的参数并放弃解引用吗?提前致谢!
struct Node{
int key;
struct Node *next;
};
struct Node* reverse(struct Node** head){
Node *parent = *head;
Node *me = parent->next;
Node *child = me->next;
parent->next = NULL;
while(child) {
me->next = parent;
parent = me;
me = child;
child = child->next;
}
me->next = parent;
*head = me;
return *head;
}
最佳答案
如果您没有传入 Node**
参数而仅使用 Node*
参数,则此行
*head = me;
需要实现为
head = me;
但是,由于 head
将按值传递,这会导致 head
的副本被传递给功能。然后修改您的函数 makea 将仅适用于此副本,而不适用于您传递的参数。
每当您需要一个函数来修改参数时,您都需要通过引用或通过指针传递它。在您的情况下,您需要 Node**
来修改它指向的 Node*
。
您还可以使用对 Node*
参数的引用。
作为一个荒谬的例子,考虑这个函数
void ChangePointer(int* x)
{
x = NULL;
}
void ChangePointer_2(int** x)
{
*x = NULL;
}
int main()
{
int* p = new int(1);
ChangePointer(p);
// p is not NULL. The function changed the copy
// of p because it was passed by value.
ChangePointer_2(&p);
// now p == NULL;
}
关于c - 指向作为操作链表的函数参数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21785485/