C语言—链表实现学生成绩管理(并求出排名最高的三位)
在这里插入代码片#include <stdio.h>
//#include<malloc.h>
#include <stdlib.h>
#include<string.h>
//void Pfree(struct Student *PStudent);
typedef struct Student
{
int ID;
char name[10];
float score;
struct Student *pNextNode;
} Student, *PStudent;
//建立节点
PStudent ByeNode(int _ID, char _name[], float _score)
{
PStudent pNewNode = (PStudent)malloc(sizeof(struct Student));
if (NULL != pNewNode)
{
pNewNode->ID = _ID;
strcpy(pNewNode->name , _name);
pNewNode->score = _score;
pNewNode->pNextNode = NULL;
}
return pNewNode;
}
// 尾插法建立单链表
void InsertTail(PStudent* pHead, int _ID, char _name[], float _score)
{
PStudent pNode = NULL;
PStudent pNewNode = NULL;
// assert(pHead);
if (NULL == (*pHead))
{
*pHead = ByeNode(_ID, _name, _score);
}
else
{
pNode = *pHead;
while (NULL != pNode->pNextNode)
{
pNode = pNode->pNextNode;
}
pNewNode = ByeNode(_ID, _name, _score);
pNode->pNextNode = pNewNode;
}
}
void SortList(PStudent pHead)
{
int IDTemp;
char nameTemp[10];
float scoreTemp;
int flag = 0;
PStudent pTailNode = NULL;
if (NULL == pHead)
{
return ;
}
else
{
flag = 0;
pTailNode = NULL;
while (pTailNode != pHead)
{
PStudent pPreNode = pHead;
while (pPreNode->pNextNode != pTailNode)
{
PStudent pCurNode = pPreNode->pNextNode;
if (pPreNode->score < pCurNode->score)
{
IDTemp = pPreNode->ID;
strcpy(nameTemp , pPreNode->name);
scoreTemp = pPreNode->score;
pPreNode->ID = pCurNode->ID;
strcpy(pPreNode->name , pCurNode->name);
pPreNode->score = pCurNode->score;
pCurNode->ID = IDTemp;
strcpy(pCurNode->name, nameTemp);
pCurNode->score = scoreTemp;
flag = 1;
}
pPreNode = pPreNode->pNextNode;
}
if (0 == flag)
{
break;
}
pTailNode = pPreNode;
}
}
}
//从头到尾打印单链表
void PrintList(PStudent pHead, int n)
{
int count = 0;
PStudent tempPnode = NULL;
tempPnode = pHead;
if (NULL != pHead)
{
while (tempPnode != NULL)
{
if (count < n)
{
printf("%-5d %-8s %-4.2f\n", tempPnode->ID, tempPnode->name, tempPnode->score);
tempPnode = tempPnode->pNextNode;
count++;
}
else if (count == n)
{
break;
}
}
}
}
void Pfree(struct Student *PStudent
{
struct Student *p, *q;
p = PStudent;
while (p->pNextNode != NULL)
{
q = p->pNextNode;
p->pNextNode = q->pNextNode;
free(q);//1
}
free(p);
}
int main(void)
{
PStudent pList1 = NULL;
PStudent tempPnode = NULL;
int i = 0;
int tempID = 0;
char tempname[10];
float tempscore;
int n = 0;
printf("请输入学生人数:\n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("请输入第%d个学生的ID、姓名和成绩:", i + 1);
scanf("%d %s %f", &tempID, tempname, &tempscore);
// printf("%d %s %f\n", tempID, tempname, tempscore);
InsertTail(&pList1, tempID, tempname, tempscore);
}
printf("所有学生的成绩:\n");
printf("ID 姓名 成绩\n");
PrintList(pList1, n);
SortList(pList1);
printf("前三名学生的成绩:\n");
printf("ID 姓名 成绩\n");
PrintList(pList1, 3);
Pfree(pList1);
return 0;
}