c - 我在链表中插入数据的程序不起作用
问题描述
以下代码不起作用。链表使用一个名为 node 的结构,它有两个字段int data
和struct 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;
}
}
解决方案
你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);