供参考:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stuInfo{
char id[12]; //数据成员
char name[15];
float score;
struct stuInfo* next;//指针成员
};
void createList(struct stuInfo** L)//创建链表
{
(*L) = (struct stuInfo*)malloc(sizeof(struct stuInfo));
(*L)->next = NULL;
}
void readfile(struct stuInfo *L) //读文件到链表
{
FILE* fp;
struct stuInfo* pL = L, * pnew = NULL;
fp = fopen("stuinfo.txt", "r");
if (fp == NULL) {
printf("文件打开失败!\n");
return;
}
while (pL->next) pL = pL->next;
while (1) {
pnew = (struct stuInfo*)malloc(sizeof(struct stuInfo));
pnew->next = NULL;
if (fscanf(fp, "%12s%15s%f", pnew->id, pnew->name, &pnew->score) != 3) {
free(pnew);
break;
}
else {
pL->next = pnew;
pL = pnew;
}
}
fclose(fp);
}
void deletestuid(struct stuInfo* L) //删除学号为xxxxx的结点
{
int flg = 0;
char id[12] = { 0 };
struct stuInfo* pL = L, * pT = NULL;
printf("请输入要删除的学号:");
scanf("%s", id);
while (pL->next) {
if (strcmp(pL->next->id, id) == 0) {
pT = pL->next;
pL->next = pT->next;
free(pT);
flg = 1;
}
else
pL = pL->next;
}
if (!flg)
printf("未找到学号:%s 的记录。\n", id);
else
printf("删除成功!\n");
}
void bbsortList(struct stuInfo* L)//按成绩冒泡排序函数
{
struct stuInfo* pL, * tail = NULL, * pNext;
while ((L->next->next) != tail) {
pL = L;
pNext = L->next;
while (pNext->next != tail)
{
if (pNext->score > pNext->next->score)
{
pL->next = pNext->next;
pNext->next = pNext->next->next;
pL->next->next = pNext;
pNext = pL->next;
}
pNext = pNext->next;
pL = pL->next;
}
tail = pNext;
}
}
void writefile(struct stuInfo* L) //写文件,将链表内容保存到文件
{
FILE* fp;
struct stuInfo* pL = L;
fp = fopen("score.txt", "w");
if (fp == NULL) {
printf("文件打开失败!\n");
return;
}
while (pL->next) {
fprintf(fp, "%s %s %f\n", pL->next->id, pL->next->name, pL->next->score);
pL = pL->next;
}
fclose(fp);
}
void printList(struct stuInfo* L)
{
struct stuInfo* p = L;
while (p->next) {
printf("%s %s %7.2f\n", p->next->id,p->next->name, p->next->score);
p = p->next;
}
}
int main()
{
struct stuInfo* L = NULL;//(1)线性链表的定义
createList(&L); //(1) 线性表创建
readfile(L); //(2) 将存放在磁盘的文件“stuinfo.txt”信息逐条读入存入到线性链表中
deletestuid(L); //(3) 将学号为‘xxxxx’的节点删除
bbsortList(L); //(4) 冒泡排序,对链表升序排序
writefile(L); //(5) 将线性链表信息存储到磁盘“score.txt”文件中
printList(L);
return 0;
}