自己写老是发生段错误,不知道为啥。参考了大佬的代码写了一个就没问题,想不明白。

#include <stdio.h>

#include<stdlib.h>

struct node

{

    int value;

    struct node* next;

};

void insert(struct node*head,int a,int b)

{

    struct node* new_node;

    while(head!=NULL)

    {

        if(head->value==b )

        {

            new_node=malloc(sizeof(struct node));

            new_node->value=a;

            new_node->next=head->next;

            head->next=new_node;

            break;

        }

        else

        head=head->next;

    }

}

void delete(struct node*head,int c)

{

    struct node *pre,*cur;

    for(pre=NULL,cur=head;cur!=NULL;pre=cur,cur=cur->next)

    {

        if(cur->value==c)

        {

            pre->next=cur->next;

            free(cur);

        }

    }

}

int main()

{

    int n,headval,target;

    scanf("%d %d",&n,&headval);

    struct node* head;

    head=malloc(sizeof(struct node));

    head->value=headval;

    head->next=NULL;

    for(int i=0;i<n-1;i++)

    {

        int a,b;

        scanf("%d %d",&a,&b);

        insert(head,a,b);

    }

    scanf("%d",&target);

    delete(head,target);

    for(;head!=NULL;head=head->next)

    {

        printf("%d ",head->value);

    }

    return 0;

}