数据结构学习录(一)——用链表将学生的成绩进行排队2 C程序

数据结构学习录(一)——用链表将学生的成绩进行排队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);
  	
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值