问题是输入学生信息成绩,按照平均分排序。
我的思路是根据结构体成员平均分,找到单链表中比这个平均分大的第一个数,然后把结构体插入到单链表中。
帮帮萌新,谢谢。
#include <stdio.h>
#include <stdlib.h>
struct Sorce
{
int chinese;
int math;
int english;
};
struct Student
{
int num;
char name[20];
struct Sorce*sorce;
float average;
struct Student*next;
};
void getInput(struct Student*student);
void getInput(struct Student*student)
{
printf("请输入学号");
scanf("%d",&student->num);
printf("请输入名字");
scanf("%s",student->name);
printf("请输入语文数学英语成绩");
scanf("%d %d %d",&student->sorce->chinese,&student->sorce->math,&student->sorce->english);
student->average=(student->sorce->chinese+student->sorce->math+student->sorce->english)/3;
}
void addStudent(struct Student**list);
void addStudent(struct Student**list)
{
struct Student*previous;
struct Student*current;
struct Student*new;
current=*list;
previous=NULL;
new=(struct Student*)malloc(sizeof(struct Student));
if(new==NULL)
{
printf("内存分配失败\n");
exit(1);
}
getInput(new);
while(current!=NULL && (current->average)<(new->average))
{
previous=current;
current=current->next;
}
new->next=current;
if(previous==NULL)
{
*list=new;
}
else
{
previous->next=new;
}
}
void printStu(struct Student*list);
void printStu(struct Student*list)
{
struct Student*current;
current=list;
while(current!=NULL)
{
printf("%d %s %d %d %d\n",current->num,current->name,current->sorce->chinese,current->sorce->math,current->sorce->english);
current=current->next;
}
putchar('\n');
free(current);
}
int main()
{
struct Student*list=NULL;
int ch;
while(1)
{
printf("是否录入学生信息(Y/N)");
do
{
ch=getchar();
}
while(ch!='Y' && ch!='N');
if(ch=='Y')
{
addStudent(&list);
}
else
{
break;
}
}
printStu(list);
return 0;
}