从早上起我就一直在尝试修复此代码,但可以完成。所以,最后我需要一些帮助来找出错误。代码编译时没有错误,但是当我从终端运行它时,我收到一条错误消息“段错误:11”
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
};
struct Node *head;
void Insert(int data);
void Print();
int main()
{
head = NULL; //list is empty
Insert(3);
Insert(5);
Insert(2);
Insert(8);
Print();
return 0;
}
void Insert(int data)
{
struct Node *temp = malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
struct Node *temp1 = head;
while(temp1 != NULL)
{
temp1= temp1->next;
}
temp1->next = temp;
}
void Print()
{
struct Node *temp =head;
while(temp != NULL)
{
temp = temp->next;
printf("%d", temp->data);
}
}
最佳答案
您绝不能将
head
设置为NULL
以外的任何值。(即使您修复了上述问题)当您到达
temp1->next = temp; 时,
.temp1
也保证为NULL
附注我不认为将变量称为 temp
、temp1
等是一个很好的做法。从这些名称中不可能看出它们的功能是什么。
关于c - 在单链表末尾插入一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26193712/