链表的搜索与删除 链表的清除

链表的搜索与删除

#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时我们就成功把链表清除了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值