//*作者:冰糖
//*日期:2018年12月1日
//*章节:第九章
//*题号:12
//*题目:建立一个链表,每个结点包括:学号,姓名,性别,年龄。输入一个年龄,如果链表中的结点包含此年龄,则将此结点删去。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N sizeof(struct student)
struct student
{
int num;
char name[20];
char sex[1];
int age;
struct student *next;
};
int num;
int n;
int main()
{
struct student *creat();
struct student *dele(struct student *head);
void print(struct student *h);
struct student *hhh,*si;
hhh=creat();
printf("\n链表的信息为:\n");
print(hhh);
printf("\n请输入要删除的年龄:\n");
scanf("%d",&num);
si=dele(hhh);
printf("\n删除后链表的信息为:\n");
print(si);
return 0;
}
struct student *creat()
{
struct student *head,*p1,*p2;
head=NULL;
p1=p2=(struct student *)malloc(N);
printf("请输入第1个结点的学号,姓名,性别,年龄:\n");
scanf("%d %s %s %d",&p1->num,&p1->name,&p1->sex,&p1->age);
while(p1->num!=0){
n++;
printf("请输入第%d个结点的学号,姓名,性别,年龄:(学号为零时终止)\n",n+1);
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(N);
scanf("%d %s %s %d",&p1->num,&p1->name,&p1->sex,&p1->age);
}
p2->next=NULL;
return head;
}
struct student *dele(struct student *head)
{
struct student *p1,*p2;
if(head==NULL)
{
printf("空表.\n");
return NULL;
}
p1=head;
while(p1->age!= num && p1->next!=NULL)
{ p2=p1;
p1=p1->next;
}
if(p1->age==num)
{ if(p1==head)
head=p1->next;
else
p2->next = p1->next;
printf("含有年龄%d的链表已被删除。\n", p1->age);
free(p1);
}
else
printf("含有年龄%d的链表未找到。\n", num);
return(head);
}
void print(struct student *h)
{ struct student *p = h;
if(p == NULL)
printf("空表\n");
while(p != NULL)
{
printf("%d %s %s %d\n",p->num,p->name,p->sex,p->age);
p = p->next;
}
printf("\n");
}
C语言程序设计第四版(谭浩强)9.12 建立一个链表,每个结点包括:学号,姓名,性别,年龄。输入一个年龄,如果链表中的结点包含此年龄,则将此结点删去。
最新推荐文章于 2021-12-13 20:03:33 发布