简单链表中的细分错误?

我正在尝试实现一个简单的链表。当我尝试编译它不显示任何错误时。但是当运行它时,它给分割错误。我分析了代码,但我找不到任何错误,可能在我这边是错误的,我不知道。 请帮助我找到代码中的错误。 预先感谢所有建议

#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 data\n");
  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 null\n");
    return;
  }

  struct node* new_node;
  new_node = (struct node*)malloc(sizeof(struct node));

/*  printf("Enter the data\n");
  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 data\n");
  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 print\n");
   }

   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;
}
chen123321bin 回答:简单链表中的细分错误?

您将segv插入了append函数中:

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;
}
本文链接:https://www.f2er.com/3056221.html

大家都在问