#include?<malloc.h>
typedef?struct?student
{
int?id;
int?score;
struct?student?*next;
}STU;
int?stuIndex;
void?inputStuInfo(STU?*stuHead);//輸入學生信息
void?orderStuInfo(STU?*stuHead);//按照分數高到低順序重組鏈表
void?printStuInfo(STU?*stuHead,int?flag);//打印學生信息。參數flag=0:正常打印鏈表信息。flag!=0:打印排序後的名次信息
int?main()
{
STU?*stuHead=(STU?*)malloc(sizeof(STU));
stuHead->next=NULL;
stuIndex=1;
inputStuInfo(stuHead);
printf("--打印原始輸入的鏈表!--\n");
printStuInfo(stuHead,0);
printf("--開始按分數降序排列!--\n");
orderStuInfo(stuHead);
printf("--鏈表按降序重組完成!--\n");
printf("--打印降序排序的鏈表!--\n");
printStuInfo(stuHead,1);
return?0;
}
void?orderStuInfo(STU?*stuHead)
{
STU?*stuSave1=NULL,*stuSave2=NULL,stuSave3;
stuSave1=stuHead;
while(stuSave1->next!=NULL)//冒泡排序
{
stuSave2=stuSave1->next;
while(stuSave2->next!=NULL)
{
if(stuSave1->next->score<stuSave2->next->score)//交換成員值,保留原鏈表指針值
{
stuSave3=*(stuSave1->next);
stuSave1->next->id=stuSave2->next->id;
stuSave1->next->score=stuSave2->next->score;
stuSave2->next->id=stuSave3.id;
stuSave2->next->score=stuSave3.score;
}
stuSave2=stuSave2->next;
}
stuSave1=stuSave1->next;
}
}
void?printStuInfo(STU?*stuHead,int?flag)
{
int?i=1;
while(stuHead->next!=NULL)
{
if(flag==0)
printf("學生%d,成績%d\n",stuHead->next->id,stuHead->next->score);
else
printf("第%d名,學生%d,成績%d\n",i++,stuHead->next->id,stuHead->next->score);
stuHead=stuHead->next;
}
}
void?inputStuInfo(STU?*stuHead)
{
int?score;
STU?*stuNew=NULL,*stuTail=NULL;
while(1)
{
printf("輸入學生%d的成績:(輸入負數結束輸入)",stuIndex);
scanf("%d",&score);
if(score<0)
break;
stuNew=(STU?*)malloc(sizeof(STU));
stuNew->score=score;
stuNew->id=stuIndex;
stuNew->next=NULL;
if(stuHead->next==NULL)
stuHead->next=stuNew;
else
stuTail->next=stuNew;
stuTail=stuNew;
stuIndex++;
}
}