链表嵌套实现一个年级内各班级学生语文、数学和英语成绩录入,寻找出一个年级内学生三科总分的最高分、最低分以及平均分。
程序员文章站
2022-07-16 19:21:01
...
链表嵌套实现一个年级内各班级学生语文、数学和英语成绩录入,寻找出一个年级内学生三科总分的最高分、最低分以及平均分。
思路:使用头插法创建一个学生的链表,节点个数便是学生人数。使用同样的方法创建班级的链表,每一个班级中包含该班学生的链表头。最后遍历两个链表打印数据。
代码如下:
#include <stdio.h>
#include <stdlib.h>
/**********定义结构体**********/
struct class
{
struct student *st;
struct class *next;
};
struct student
{
int yuwen;
int shuxue;
int yingyu;
int add;
struct student *next;
};
/**********头插法创建学生链表**********/
struct student* insertSt(struct student *head,int i)
{
struct student *new = head;
new = (struct student *)malloc(sizeof(struct student));
printf("第%d名同学语文成绩:\n",i+1);
scanf("%d",&(new->yuwen));
printf("第%d名同学数学成绩:\n",i+1);
scanf("%d",&(new->shuxue));
printf("第%d名同学英语成绩:\n",i+1);
scanf("%d",&(new->yingyu));
new->add = (new->yuwen)+(new->shuxue)+(new->yingyu);
if(head == NULL){
head = new;
return head;
}else{
new->next = head;
head = new;
return head;
}
return head;
}
struct student* inputSt()
{
int i,num;
printf("请输入该班人数:");
scanf("%d",&num);
struct student *st = NULL;
for(i=0;i<num;i++){
st=insertSt(st,i);
}
return st;
}
/**********头插法创建班级链表**********/
struct class* insertCl(struct class *head,int i)
{
struct student *st = NULL;
struct class *new = NULL;
new = (struct class *)malloc(sizeof(struct class));
printf("输入%d班成绩:\n",i+1);
st = inputSt(st);
new->st = st;
if(head == NULL){
head = new;
return head;
}else{
new->next = head;
head = new;
return head;
}
return head;
}
struct class* inputCl()
{
int i,ban;
printf("请输入班级数目:\n");
scanf("%d",&ban);
struct class *cl = NULL;
for(i=0;i<ban;i++){
cl=insertCl(cl,i);
putchar('\n');
}
return cl;
}
/**********输出打印结果**********/
void printFen(struct class *cl)
{
int i=0;
int max = cl->st->add;
int min = max;
float ave = 0;
while(cl != NULL){
while(cl->st != NULL){
if(max < cl->st->add){
max = cl->st->add;
}
if(min > cl->st->add){
min = cl->st->add;
}
ave =(float) ave+cl->st->add;
++i;
cl->st = cl->st->next;
}
cl = cl->next;
}
ave =(float)ave/i;
printf("年级总分最高分:%d\n",max);
printf("年级总分最低分:%d\n",min);
printf("年级总分平均分:%f\n",ave);
}
int main()
{
struct class *cl=NULL;
cl = inputCl();
printFen(cl);
return 0;
}
运行程序: