【问题标题】:pointer to pointers for singly linked list in C [duplicate]指向C中单链表指针的指针[重复]
【发布时间】:2013-08-07 15:52:12
【问题描述】:

我有一个关于 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 ,而不是 struct node * list 。我想知道为什么 ?哪一个是正确的,如果它们都是正确的,它们之间有什么区别,我将我的实现与我在这里编写的示例 main 一起使用,它工作正常但我不知道为什么要使用指向指针的指针?提前致谢。

【问题讨论】:

  • head=malloc(sizeof(struct node)); head 未正确初始化。
  • @PeterMiehle 我不认识你在这里链接的问题。抱歉重复,但我没有这样做重复的目的

标签: c pointers linked-list


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    What is the reason for using a double pointer when adding a node in a linked list?

    【讨论】:

      【解决方案3】:

      给定

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

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

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

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

      【讨论】:

        【解决方案4】:

        这对我来说看起来非常好。

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

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

        【讨论】:

        【解决方案5】:

        这有点自然,如果你调用“head = NULL; insert(&head, data);”然后 head 指向第一个元素。所有打算改变内容的函数都应该被间接调用。 但是:这是编码约定的问题。有人喜欢热的,有人喜欢冷的。 head=insert(head, data); 的问题也就是说,当你忘记 "head="

        时,那个头是不可用的

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-28
          • 1970-01-01
          • 2012-08-11
          • 1970-01-01
          • 2010-10-27
          • 1970-01-01
          • 2021-08-14
          相关资源
          最近更新 更多