-1
此代码有什么问题。插入操作期间,插入第二个元素时,程序停止,Windows显示程序已停止工作。在构建日志中显示Process terminated with status -1073741510
,有时Process terminated with status 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;
}
}
您的代码由于错误而崩溃 - 如果您在调试器中运行该代码,它会告诉您哪一行崩溃,并且希望能够看到您所做的真正明显的错误。 –
temp2-> link = temp;':'temp2'在while循环后是'NULL'。 – BLUEPIXY
太多的全局变量! 'print()'中的'temp1'应该是'print()'的本地。将'head'传递给函数也会更好。 'insert()'中的'temp'和'temp2'也应该是局部变量。在这里,您需要小心处理'头部' - 最好将它传递给函数并返回新的头部(除了将第一个元素添加到列表时,与旧头部相同)。你可以定义'end',但不要使用它。这是马虎。 –