9.12建立一个链表,每个结点包括:学号、姓名、性别、年龄。输入一个年龄,如果链表中的结点所包含的年龄等于此年龄,则将此结点删去。

//C程序设计第四版(谭浩强)
//章节:第九章 用户自己建立数据类型 
//题号:9.12
//题目:建立一个链表,每个结点包括:学号、姓名、性别、年龄。输入一个年龄,
//如果链表中的结点所包含的年龄等于此年龄,则将此结点删去。 
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct student)
struct student
{
	long num;
	char name[10];
	char sex;
	int age;
	struct student *next;
};
struct student *create()	//创建链表函数 
{
	struct student *head=NULL,*p1,*p2;
	int n=0;
	printf("input num,name,sex,age(if num=0 stop):\n");
	p1=p2=(struct student *)malloc(LEN);
	scanf("%ld %s %c %d",&p1->num,p1->name,&p1->sex,&p1->age);
	while(p1->num!=0)
	{
		n=n+1;
		if(n==1)
			head=p1;
		else
			p2->next=p1;
		p2=p1;
		p1=(struct student *)malloc(LEN);
		scanf("%ld %s %c %d",&p1->num,p1->name,&p1->sex,&p1->age);
	}
	p2->next=NULL;
	return head;
}
struct student *search(struct student *head,int x)	//查找结点函数 
{
	struct student *p;
	p=head;
	while(p!=NULL)
	{
		if(p->age==x)
			return p;
		p=p->next;
	}
	return NULL;
}
struct student *del(struct student *head,int x)	//删除结点函数 
{
	struct student *p1,*p2;
	if(head==NULL)	//如果原链表为空 
	{
		printf("list is null!\n");
		return NULL;
	}
	p1=head;
	while((p1->age!=x)&&p1->next!=NULL)
	{
		p2=p1;
		p1=p1->next;
	}
	if(p1->age==x)
	{
		if(p1==head)	//如果删除首结点 
			head=p1->next;
		else
			p2->next=p1->next;	//如果删除其他结点 
		free(p1);
	}
	else	//如果没有找到相同年龄结点 
		printf("age %d is not found!\n",x);
	return head;
}
void print(struct student *head)	//输出链表函数 
{
	struct student *p;
	p=head;
	printf("output list:\n");
	while(p!=NULL)
	{
		printf("%ld\t%s\t%c\t%d\n",p->num,p->name,p->sex,p->age);
		p=p->next;
	}
}
int main()
{
	struct student *head;
	head=create();
	print(head);
	int x;
	printf("input age to delete:\n");
	scanf("%d",&x);
	do
	{
		head=del(head,x);
	}while(search(head,x)!=NULL);
	print(head);
	return 0;
}
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值