我正在尝试创建一个简单的链表并在链表末尾插入一个节点。我遇到了段错误。
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *link;
};
void create(struct node *head){
struct node* second = NULL;
struct node* last = NULL;
second = (struct node*)malloc(sizeof(struct node));
last = (struct node*)malloc(sizeof(struct node));
second -> data = 2;
last -> data = 3;
head -> link = second;
second -> link = last;
last -> link = NULL;
}
void insert_ending(struct node *head){
struct node* temp = NULL;
struct node* temp1 = NULL;
temp1 = (struct node*)malloc(sizeof(struct node));
temp1 -> data = 5;
temp1 -> link = NULL;
temp = head;
while(temp != NULL){
temp = temp -> link;
}temp -> link = temp1;
}
void PrintList(struct node *head){
while( head != NULL ){
printf(" %d -->", head -> data);
head = head -> link;
}
printf("\n");
}
int main(){
struct node* head = NULL;
head = (struct node*)malloc(sizeof(struct node));
head -> data = 1;
head -> link = NULL;
create(head);
PrintList(head);
insert_ending(head);
PrintList(head);
return 0;
}
我遇到了段错误。输出结果如下。
1 --> 2 --> 3 --> Segmentation fault (core dumped)
最佳答案
在您的插入功能中,您需要更改为:
temp = head;
while(temp -> link != NULL){
temp = temp -> link;
}
temp -> link = temp1;
原因是当你用 while 循环直到 temp == null 时,你不能之后做:temp -> link 因为 temp 已经是 null。
关于c - 在C中实现链表时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30286947/