我正在尝试实现一个简单的链表。当我尝试编译时,它没有显示任何错误。但当运行它时,它会出现分段错误。我分析了代码,但我找不到任何错误,可能是我错了,我不知道。请帮我找出代码中的错误。提前感谢的所有建议
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
void push(struct node** first, int data){
struct node* new_node;
new_node =(struct node*)malloc(sizeof(struct node));
/*printf("Enter the datan");
scanf("%d",&new_node->data);*/
new_node->data = data;
new_node->next= NULL;
if(*first==NULL){
*first = new_node;
return;
}
new_node->next= *first;
*first = new_node;
}
void insert_node(struct node* prv, int data){
if(prv==NULL){
printf("previous node cannot be nulln");
return;
}
struct node* new_node;
new_node = (struct node*)malloc(sizeof(struct node));
/* printf("Enter the datan");
scanf("%d",&new_node->data); */
new_node->data = data;
new_node->next = prv->next;
prv->next = new_node;
}
void append(struct node** first, int data){
struct node* last;
last = (struct node*)malloc(sizeof(struct node));
/* printf("Enter the datan");
scanf("%d",&last->data); */
last->data = data;
last->next = NULL;
struct node* pre = *first;
if(*first == NULL){
*first = last;
}
while(pre->next!=0)
{pre = pre->next;}
last->next = pre->next;
pre->next = last;
}
void print(struct node* first){
if(first==NULL){
printf("There is no linked list to printn");
}
while(first!=NULL){
printf("%d ",first->data);
first = first->next;
}
printf("n");
}
int main()
{
struct node* first=NULL;
append(&first, 6);
push(&first, 7);
push(&first, 1);
append(&first, 4);
insert_node(first->next, 8);
printf("The Linked List is: n");
print(first);
return 0;
}
您在append函数中获得了segov:
void append(struct node** first, int data){
struct node* last;
last = (struct node*)malloc(sizeof(struct node));
last->data = data;
last->next = NULL;
struct node* pre = *first; // <-- pre = NULL
if(*first == NULL){
*first = last;
}
while(pre->next!=0)
{pre = pre->next;} //<-- referencing NULL
last->next = pre->next;
pre->next = last;
}
解决方案:在if.中添加退货
if(*first == NULL){
*first = last;
return;
}