/*###########################################################################################################
# #
#实验内容: #
#设计一个算法,在单链表存储结构上实现冒泡排序。 #
#学生的考试成绩表由学生的学号、姓名和成绩组成, #
#设计一个程序对给定的n个学生信息实现: #
#1)按分数高低次序,打印出每个学生在考试中的排名,分数相同的为同一名次,同一名次的学生按学号从小到大排列。 #
#2)按照名次列出每个学生的名次、学号、姓名和成绩。 #
# #
############################################################################################################*/
//student.h
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//结构体学生信息studnet_dat
struct Student_dat
{
string number;
string name;
// char gender;
float score;
Student_dat *next;
};
//定义学生类
template<class T>
class Student
{
public:
void setstu(Student_dat *);
Student_dat *stulist(Student_dat *&);
void bubbleSort(Student_dat *);//冒泡排序
void stumean(Student_dat *);
void display(Student_dat *);
void getmean();
private:
float mean;//平均分
};
template <class T>
void Student<T>::setstu(Student_dat *a)
{
cout<<"学号:";
cin>>a->number;
if (a->number=="0")return ;
cout<<"姓名:";
cin>>a->name;
// cout<<"性别(男/女):";
// cin>>a->gender;
cout<<"分数:";
cin>>a->score;
}
template <class T>
void Student<T>::display(Student_dat *top)
{
Student_dat *p=top;
p=p->next;
int count=0;
cout<<"序号"<<'\t'<<"学号"<<'\t'<<"姓名"<<'\t'<<"成绩"<<endl;
while (p!=NULL)
{
cout<<setw(2)<<++count<<'\t';
cout<<p->number<<'\t'<<p->name<<'\t'<<p->score<<endl;
p=p->next;
}
}
template <class T>
void Student<T>::getmean()
{
cout<<"平均分:"<<mean<<endl;
}
template <class T>
void Student<T>::stumean(Student_dat *top)
{
if (top->next==NULL)
return;
Student_dat *p=top;
p=p->next;
double sum=0;
int i=0;
while (p!=NULL)
{
i++;
sum+=p->score;
p=p->next;
}
mean=sum/(float)i;
return;
}
template <class T>
Student_dat *Student<T>::stulist(Student_dat * &top)//单链建立学生信息
{
Student_dat *p,*star;
star=top;
top->next=star;
cout<<"-----请输入学生信息-----"<<endl;
while (1)
{
p=new Student_dat;
setstu(p);
if (p->number=="0")break;
star->next=p;
star=p;
cout<<"----------"<<endl;
};
star->next=NULL;
return top;
}
template <class T>
void Student<T>::bubbleSort(Student_dat *top)//冒泡排序
{
cout<<"-----升序排列后的数据-----"<<endl;
int num=0;
Student_dat *p=top;
Student_dat *r;
Student_dat *s;
Student_dat q;//用以中转数据
string tempnum;
string tempname;
float tempscore;
float tempscore1;
float tempscore2;
while (p!=NULL)
{
s=p;
r=p->next;
while(r!=NULL)
{
tempscore1=s->score;
tempscore2=r->score;
if (tempscore2<tempscore1)
{
s=r;//一趟循环过后s最终指向单链表中的最值
}
r=r->next;
}
if (s!=p)
{
q=(*p);//交换数据
tempnum=s->number;p->number=tempnum;
tempname=s->name;p->name=tempname;
tempscore=s->score;p->score=tempscore;
tempnum=q.number;s->number=tempnum;
tempname=q.name;s->name=tempname;
tempscore=q.score;s->score=tempscore;
}//p与s的数据项全部调换
p=p->next;
}
}
//main.cpp
#include "student.h"
void main()
{
Student_dat *top=new Student_dat;
Student<Student_dat> a;
a.stulist(top);
a.stumean(top);
a.display(top);
a.getmean();
a.bubbleSort(top);a.display(top);
a.getmean();
delete top;
}