链表的搜索与删除
#include<stdlib.h>
#include<string.h>
struct x{
int n;char k[20];
int m;
struct x *next;
};
int main()
{
int n,m;char k[20];
struct x *head,*tail,*p;
head=tail=NULL;
scanf("%d",&m);
while(m!=-1){ //这个地方我们要写清楚跳出的条件
p=(x*)malloc(sizeof(struct x)); //将结构的首地址给p
scanf("%s %d",k,&n);
p->m=m;
p->n=n;strcpy(p->k,k);
p->next=NULL;
if(head==NULL)
head=p;
else
tail->next=p; //这里的tail相当于上一个p
tail=p;
scanf("%d",&m);
}
scanf("%d",&n);
for(tail=NULL,p=head;p!=NULL;tail=p,p=p->next){
if(p->n==n){
if(tail){ //这里我们的tail仍然是上一个p
tail->next=p->next;
}else{
head=p->next;
}
}
free(p);break;
}
for(p=head;p!=NULL;p=p->next){
printf("%d ",p->n);
}
return 0;
}
删除一个结点就是让它上一个的next指向它下一个的首地址;
这里我们要重点看一下当删除的是第一个这个就是特殊情况,
我们需要判断一下用中间替代上一个p的tail看其是否为null。
链表的清除
for(p=head;p;p=tail){
tail=p->next;
free(p);
}
p为NULL时我们就成功把链表清除了。