LZ参考下,用链表做的
#include <stdio.h>
#include <stdlib.h>
typedef struct name_score
{
char name[10];
float score;
struct name_score *next;
}LNode,*LinkList;
int num;//输入数据个数
LinkList creat()//创建链表
{
LinkList L = NULL;//表头置空
LinkList newdata=NULL;
LinkList lastdata=NULL;
int i;
scanf("%d",&num);fflush(stdin);
for(i = 0;i < num;i++)
{
newdata = (LinkList)malloc(sizeof(LNode));//开辟新空间
scanf("%s %f",newdata->name,&newdata->score);fflush(stdin);
if(L == NULL)
{
L = newdata;
}
else
{
lastdata->next = newdata;
}
lastdata = newdata;
}
if(lastdata->next != NULL)
{
lastdata->next = NULL;
}
return L;
}
void sort(LinkList L)//记录最大的三个数,并显示
{
LinkList max = L;
LinkList middle = L;
LinkList min = L;
LinkList thisdata = L->next;
int i;
for(i = 0;i < num-1;i++)//共num个数,比较num-1次,max指向最大的数
{
if(max ->score < thisdata->score)
{
max = thisdata;
}
thisdata = thisdata->next;
}
thisdata = L->next;
if(max == L)//最大数为链表第一个数时
{
middle = L->next;
min = L->next;
}
for(i = 0;i < num-1;i++)//middle指向次大的数
{
if(thisdata != max)
{
if(middle ->score < thisdata->score)
{
middle = thisdata;
}
}
thisdata = thisdata->next;
}
thisdata = L->next;
if((middle == L) || (middle == L->next))//次大数为链表第一个或第二个数时
{
min = L->next->next;
}
for(i = 0;i < num-1;i++)//min指向次大的数
{
if(thisdata != max)
{
if(thisdata != middle)
{
if(min ->score < thisdata->score)
{
min = thisdata;
}
}
}
thisdata = thisdata->next;
}
printf("%s %f\n",max->name,max->score);
printf("%s %f\n",middle->name,middle->score);
printf("%s %f\n",min->name,min->score);
}
main()
{
LinkList L;
L=creat();
sort(L);
}
输入输出:
8
john 9.5
tom 10
cate 6
king 7.5
peter 4
kate 5.5
jim 9
ken 7
tom 10.000000
john 9.500000
jim 9.000000
Press any key to continue