//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;
}
9.12建立一个链表,每个结点包括:学号、姓名、性别、年龄。输入一个年龄,如果链表中的结点所包含的年龄等于此年龄,则将此结点删去。
最新推荐文章于 2023-07-09 23:50:36 发布