这段代码有什么问题。在插入操作过程中,当插入第二个元素时,程序停止运行,Windows 显示程序已停止工作。在构建日志中,它显示进程终止于状态 -1073741510
,有时进程终止于状态 255
。即使主函数中有一个 return 语句。
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void insert(int);
void print();
struct node
{
int data;
struct node *link;
};
struct node *temp, *temp1, *temp2, *head, *end;
int main()
{
int i, ch, a;
head = NULL;
temp = (node*)malloc(sizeof(node));
printf("Enter the number of items");
scanf("%d", &ch);
for(i = 0; i < ch; i++)
{
printf("\nEnter the number");
scanf("%d", &a);
insert(a);
**call to insert**
print();
}
return 0;
}
void insert(int x)
{
temp = (node*)malloc(sizeof(struct node));
temp->data = x;
temp->link = NULL;
temp2 = head;
if(head == NULL)
{
head = temp;
}
else
{
while(temp2 != NULL)
{
temp2 = temp2->link;
}
temp2->link = temp;
}
}
void print()
{
temp1 = head;
printf("\nthe list is:");
while(temp1 != NULL)
{
printf("%d", temp1->data);
temp1 = temp1->link;
}
}
最佳答案
这部分功能
else
{
while(temp2 != NULL)
{
temp2 = temp2->link;
}
temp2->link = temp;
}
是错误的。退出循环后,节点 temp2
等于 NULL。因此这个声明
temp2->link = temp;
导致未定义的行为。
按以下方式更改代码片段
else
{
while(temp2->link != NULL)
{
temp2 = temp2->link;
}
temp2->link = temp;
}
main 中还有此语句
temp = (node*)malloc(sizeof(node));
没有意义并导致内存泄漏。
除了变量头之外的全局变量的声明
struct node *temp, *temp1, *temp2, *head, *end;
也没有道理。
关于c - 链表——在末尾插入一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44570660/