指向C中单链表指针的指针[重复]

2024-05-10

我有一个关于 C 中的单链表的问题。我用下面所示的代码创建了一个链表:

#include <stdio.h>
#include <stdlib.h>
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 &&data<curr->data;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 , not struct node * list。我想知道为什么 ?哪一个是正确的,如果两者都是正确的,它们之间有什么区别,我将我的实现与我在这里编写的示例 main 一起使用,它工作正常,但我不知道为什么应该使用指向指针的指针?提前致谢。


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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

指向C中单链表指针的指针[重复] 的相关文章

随机推荐