题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
自己写老是发生段错误,不知道为啥。参考了大佬的代码写了一个就没问题,想不明白。
#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;
}