c-链表分段错误-仅当使用多个链表时



因此,我编写了一个函数,在链表的末尾插入元素,并按预期工作。或者我是这么想的,直到我尝试对另一个列表使用相同的函数,这产生了一个分割错误,我不知道为什么。如果这不是最好的插入方式,请原谅我,我还在学习。

实施:

struct Node
{
int data;
struct Node* next;
};
typedef struct Node LL;
LL *makeNode(int data)
{
LL *res = malloc(sizeof(LL));
res->data = data;
res->next = NULL;
return res;
}
LL *insert(LL *head, int item)
{
if(!head)
return makeNode(item);
else if(!head->next)
{
head->next = makeNode(item);
}
else
{
LL *tmp = head;
while(tmp->next)
tmp = tmp->next;
tmp->next = makeNode(item);
}
return head;
}
void display(LL *head)
{
if(!head)
{
printf("n");
return;
}
printf("%d, ", head->data);
display(head->next);
}

以下是我在主函数中的调用方式:

int main()
{
srand(time(0));
LL *head1, *head2;
int i, n1 = 10, n2 = 10, item;
for(i=0; i<n1; i++)
{
item = rand()%10;
head1 = insert(head1, rand()%10);
}
for(i=0; i<n2; i++)
{
item = rand()%10;
head2 = insert(head2, rand()%10);
}
display(head1);
printf("2: ");
display(head2);
}

当我单独使用LL head1或LL head2进行测试时,上面的代码提供了预期的输出。但同时做这两件事会导致臭名昭著的分割错误,我不确定为什么。如有任何帮助,我们将不胜感激,提前表示感谢。

如果不存在头节点,insert()函数将创建头节点。当您将NULL指针作为第一个参数传递给insert((时,就会发生这种情况。在主函数中,head1和head2指针都是自动变量,因此在第一次调用insert((时它们将是未定义的。您应该将他们的声明更改为:

LL *head1 = NULL;
LL *head2 = NULL;

最新更新