我试图创建一个简单的链表并在列表的末尾插入一个节点。我收到了分段错误。
#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 - &gt; 2 - &gt; 3 - &gt; 分段错误(核心转储)
答案 0 :(得分:3)
,您需要更改为:
temp = head;
while(temp -> link != NULL){
temp = temp -> link;
}
temp -> link = temp1;
原因是当你循环使用while到temp == null时,你不能再执行:temp - &gt;链接因为temp已经全部为空。
答案 1 :(得分:3)
在功能&#39; insert_ending&#39;在while循环中你想要改变 条件来自:
while ( temp != NULL )
于:
while ( temp->link != NULL )
因为现在循环完成后,temp为NULL然后你尝试取消引用它(一个NULL指针)并得到一个错误。