指向C中单个链表的指针

我有一个关于C中的符号链接列表的问题。我创建了一个链接列表,其代码如下所示:

#include  #include  struct node { int data; struct node* next; }; struct node *mknode(int data) { struct node* np=malloc(sizeof(struct node)); np->data=data; np->next=NULL; return np; } struct node * insert (struct node* list,int data) { struct node *np; struct node*curr=list; struct node* prev=NULL; np=mknode(data); for(;curr &&datadata;curr=curr->next ) prev=curr; np->next=curr; if(prev) prev->next=np; else list=np; return list; } int main() { struct node* head; head=malloc(sizeof(struct node)); head=insert(head,7); head=insert(head,2); head=insert(head,4); printf("%d",head->data); printf("%d",head->next->data); printf("%d",head->next->next->data); return 0; } 

然而,当我在互联网上搜索时,我意识到,双指针用于创建链表而不是普通指针。我的意思是, struct node **list ,而不是struct node * list 。 我想知道为什么 ? 哪一个是正确的,如果它们都是真的,它们之间有什么区别,我用我在这里写的示例main的实现,它工作正常,但我不知道为什么我应该使用指针指针? 提前致谢。

有些人使用指向指针的原因是为了在不返回新指针的情况下更新节点。 在您的示例中,如果您想要更改头指针,则必须创建一个新指针,然后使头等于该指针。 使用双指针,您只需释放第二个指针指向的空间,然后更新指向新数据结构的第二个指针,这将保留原始指针

我只是在我的实现中使用单指针。

阅读此处,通过这种方式,您可以更改元素而无需创建新元素。

在链表中添加节点时使用双指针的原因是什么?

特定

 struct node { int x; }; struct node **pplist; struct node *plist; 

pplist是指向struct node的指针,而plist是指向struct node的指针。 要更改x,您需要编写

 *pplist->x = 3; plist->x = 4; 

如果您希望相同的变量指向不同的列表,或者您希望将指针传递给具有更改该指针的副作用的函数,则可以使用指向指针的指针。

这对我来说非常好。

所有指针都是某个地方的内存地址。 双指针只是另一个指向某些数据的存储器地址的存储器地址。

也许你可以发布你看到node **list ,我们可以更好地解释它,但是现在,你的代码看起来不错。

它有点自然,如果你调用“head = NULL; insert(&head,data);” 然后头指向第一个元素。 应该间接调用所有用来改变内容的函数。 但是:这是编码惯例的问题。 有些人喜欢热,有些人喜欢冷。 head = insert(head,data)的问题; 当你忘记“head =”时,那个头是无法使用的