首页 > 解决方案 > 我在链表中​​插入数据的程序不起作用

问题描述

以下代码不起作用。链表使用一个名为 node 的结构,它有两个字段int datastruct node* next。我定义了两个头节点,struct node* head1并且是struct node* head2全局的。

void insert(struct node* h, int data)  //h is the head node
{
    struct node* temp=(struct node*)malloc(sizeof(struct node));

    temp->data=data;
    temp->next=NULL;

    if(h==NULL)
    {
      h=temp;   
    }
    else
    {
      struct node* ptr=h;

      while(ptr->next!=NULL)
      {
        ptr=ptr->next; 
      }

      ptr->next=temp;
    }
}

标签: csingly-linked-list

解决方案


h是本地的,insert一旦控制退出insert功能就会被销毁。h此外,对内部进行的任何更改insert都不会影响原始头部。

解决方案:

您可以将原始头部的引用传递给以保留如下insert所做的更改。insert

   void insert(struct node **h, int data)  //h is the head node
    {
         struct node* temp=(struct node*)malloc(sizeof(struct node));
         temp->data=data;
         temp->next=NULL;

         if(*h == NULL)
         {
            *h=temp;
         }
         else
         {
            struct node* ptr = *h;
            while(ptr->next!=NULL)
            {
                ptr=ptr->next;
            }
            ptr->next=temp;
       }
    }

你打电话insert如下。

struct node *head = NULL;
insert(&head,1);

推荐阅读