首页 > 解决方案 > C中链表上的双指针

问题描述

在一个简单的链表中,为什么在插入节点时要传递一个双指针?与第二个代码有什么区别?

void push(struct node **headRef, int data);
void push(struct node *head, int data);

标签: cpointerslinked-list

解决方案


C 函数调用总是传递参数的。当您在函数内部时,您可以将来自调用者的值的副本放在新变量中。

您可以在函数内更改这些副本的值,但调用者拥有的值将保持不变。

例子:

void foo(int n)
{
    n = 1;
    printf("In foo: %d\n", n);  // Will print 1
}

void bar()
{
     int n = 42;
     printf("In bar: %d\n", n);  // Will print 42
     foo(n);
     printf("Back in bar: %d\n", n);  // Will still print 42
}

如您所见,对ninsidefoo所做的更改不会更改ninside bar

那么,如果你真的想改变n内心bar呢?

那是你而不是传递n一个指向.n

喜欢:

void foo(int *n)  // Note the *
{
    *n = 1;
    printf("In foo: %d\n", *n);  // Will print 1
}

void bar()
{
     int n = 42;
     printf("In bar: %d\n", n);  // Will print 42
     foo(&n);                    // Note the & to get a pointer to n
     printf("Back in bar: %d\n", n);  // Will now print 1
}

这也是您的代码行之间的区别:

void pushA(struct node **headRef, int data);
void pushB(struct node *head, int data);

struct node *head = NULL;
pushA(&head, 42);   // head may be changed after this call
pushB(head, 42);    // head is unchanged after this call

第一个版本可能是您想要的,即在将新元素推送到列表时,您希望将元素插入到前面,因此需要更改 head 的值。

另一种方法是让函数返回一个指向新头的指针:

struct node* push(struct node *head, int data);

struct node *head = NULL;
head = push(head, 42);

推荐阅读