题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<malloc.h>
#include<stddef.h>
struct node{
struct node * next;
int data;
};
struct link{
struct node * headnode;
int length;
};
void enlink_head(struct node * p,int b,int a){
struct node * t=p;
struct node *s=(struct node*)malloc(sizeof(struct node));
s->next=NULL;
s->data=a;
while(1){
if(t->data==b){
s->next=t->next;
t->next=s;
//printf("did insert\n");
break;
}else if(p->next!=NULL){
t=t->next;
//printf("search for the tag\n");
}else{
//printf("invalid input!\n");
break;
}
}
}
void delnode(struct node *t,int a){
struct node * p=t;
struct node * s;
int flag=1;
while(1){
if(flag==1&&p->data==a){
//printf("%d \n",t->data);
t=t->next;
//printf("%d \n",t->data);
p=t;
flag=0;
}else if(p->data!=a&&p->next!=NULL){
s=p;
p=p->next;
//printf("researching\n");
}else if(p->data==a){
//printf("deleting\n");
s->next=p->next;
if(p->next!=NULL){
//printf("continue searching\n");
p=p->next;
}
}else{
//printf("did\n");
break;
}
}
}
void printlink(struct link l){
struct node * p=l.headnode;
while(1){
printf("%d ",p->data);
if(p->next!=NULL){
p=p->next;}else{break;}
}
}
int main(){
struct link l1;
int temp,tag,delnum;
int flag=0;
//struct node * empty=NULL;
//empty=l1.headnode;
//if(empty!=NULL){printf("NULL可以经判断是否等于NUUL来完成条件判断\n");
//}else{printf("buke");
//}
while(1){
if(flag==0){
scanf("%d",&temp);
l1.length=temp;
flag++;
//printf("flag=%d\n",flag);
continue;
}else if(flag==1){
scanf("%d",&temp);
struct node *h=(struct node*)malloc(sizeof(struct node));
l1.headnode=h;
l1.headnode->next=NULL;
l1.headnode->data=temp;
flag++;
//printf("flag=%d\n",flag);
//printf("%d",l1.headnode->data);
continue;
}else if(flag<=l1.length){
scanf("%d",&temp);
scanf("%d",&tag);
enlink_head(l1.headnode,tag,temp);
//printlink(l1.headnode);
flag++;
//printf("flag=%d\n",flag);
//printf("2\n");
continue;
}else if(flag==l1.length+1){
//printf("%d",l1.length);
scanf("%d",&delnum);
if(l1.headnode->data==delnum){
l1.headnode=l1.headnode->next;
}
//printf("find the num to del %d\n",delnum);
delnode(l1.headnode,delnum);
//printf("%d \n",l1.headnode->data);
//printf("3\n");
//printf("exit\n");
break;
}else{
printf("erro");
break;
}
}
printlink(l1);
return 0;
}