我试图创建一个简单的链表,并在列表的末尾插入一个节点。我得到一个分割错误。
#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 ->分段故障(堆芯转储)
在您的插入函数中,您需要更改为:
temp = head;
while(temp -> link != NULL){
temp = temp -> link;
}
temp -> link = temp1;
的原因是,当你循环while直到temp == null时,你不能随后执行:temp -> link,因为temp已经为空了。
在while循环中的'insert_ending'函数中,您希望更改条件:
while ( temp != NULL )
:
while ( temp->link != NULL )
,因为现在一旦循环结束,temp是NULL,然后你试图解引用它(一个NULL指针)并得到一个错误。