数据结构学习录(一)——用链表将学生的成绩进行排队2 C程序
输入:
N个学生的两个成绩
输出:
按两个成绩的平均成绩排序后输出
/*学生成绩从小到大排序 链表*/
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct stu)
typedef struct{
int num;
char name[20];
float score1,score2,av;
}Student;
struct stu{
Student data;
struct stu *next;
};
int n;//人数的全局变量
struct stu *creat(void) //输入
{
struct stu *head;
struct stu *p1,*p2;
n=0;
p1=p2=(struct stu*)malloc(LEN);
printf("请输入学生的学号、姓名、成绩1、成绩2\n");
scanf("%d %s %f %f",&p1->data.num,p1->data.name,&p1->data.score1,&p1->data.score2);
p1->data.av=(p1->data.score1+p1->data.score2)/2.0;
head=NULL;
while(p1->data.num)
{
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct stu*)malloc(LEN);
printf("请输入学生的学号、姓名、成绩1、成绩2\n");
scanf("%d %s %f %f",&p1->data.num,p1->data.name,&p1->data.score1,&p1->data.score2);
p1->data.av=(p1->data.score1+p1->data.score2)/2.0;
}
p2->next=NULL;
return (head);
}
void paixu(struct stu *head)
{
struct stu *pb, *pf, temp;
pf = head;
if(head == NULL) //链表为空
{
printf("needn't order.\n");
return ;
}
if(head->next == NULL) //链表有点
{
printf("only one print, needn't order.\n");
return ;
}
while(pf->next != NULL) { //以pf指向的节点为基准节点
pb = pf->next; //pb从基准点的下一个节点开始
while(pb != NULL)
{
if(pf->data.av > pb->data.av)
{
temp = *pf;
*pf = *pb;
*pb = temp;
temp.next = pf->next;
pf->next = pb->next;
pb->next = temp.next;
}
pb = pb->next;
}
pf = pf->next;
}
return ;
}
void print(struct stu *head) //输出
{
struct stu *p;
printf("%15s %20s %6s %6s %6s\n","学号","姓名","成绩1","成绩2","平均分");
p=head;
if(head!=NULL)
{
do
{
printf("%15d %20s %6.2f %6.2f %6.2f\n",p->data.num,p->data.name,p->data.score1,p->data.score2,p->data.av);
p=p->next;
}while(p!=NULL);
}
}
int main()
{
struct stu *head;
head=creat();
paixu(head);
print(head);
}