现有结构体定义如下:
struct stuInfo
{
char id[12]; //数据成员
char name[15];
float score;
struct stuInfo *next; //指针成员
};
任务及要求:
(1)首先完成线性链表的定义和创建,确保链表的第一个节点为哨兵节点,不存放有效的数据;
(2)利用文件的相关操作,动态开辟节点存储空间,将存放在磁盘某个路径中的文件“stuinfo.txt”信息逐条读入,并依次存入到线性链表的每个节点中,信息如下;
00001 张三 100
00002 李四 99
00003 王五 100
00004 王六 89
00005 江涛 98
00006 陈琪 88
00007 祁廷 91
(3)接下来,利用键盘输入,动态开辟节点存储空间,将00008 赵四 88信息存在一个节点中,并插入到学号是‘00005’和‘00006’之间;
(4)再接下来,利用直接插入排序,对链表继续升序排序;
(5)将完整的线性链表信息从头到尾依次存储到磁盘某个路径下的“score.txt”文件中,存储格式和“stuinfo.txt”文件相同。
(6)最终将“score.txt”的内容复制粘贴到实验报告的实验结果中。
大一新生想问一下这个问题用CodeBlocks如何解决,急。谢谢大家
链表操作和文件读写。代码如下:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct stuInfo
{
char id[12]; //数据成员
char name[15];
float score;
struct stuInfo* next; //指针成员
};
//1.创建链表
struct stuInfo* CreateList()
{
struct stuInfo* head = (struct stuInfo*)malloc(sizeof(struct stuInfo));
head->next = 0;
return head;
}
//读文件
void readFile(struct stuInfo* head)
{
struct stuInfo* p, * t;
FILE* fp = fopen("stuinfo.txt", "r");
if (fp == 0)
{
printf("文件打开失败!\n");
return;
}
//获取链表尾节点
p = head;
while (p->next)
p = p->next;
//开始读文件
while (!feof(fp))
{
t = (struct stuInfo*)malloc(sizeof(struct stuInfo));
t->next = 0;
t->id[0] = 0;
fscanf(fp, "%s %s %f", t->id,t->name,&t->score);
if (strlen(t->id) == 0)
{
free(t);
}
else
{
p->next = t;
p = t;
}
}
fclose(fp);
printf("文件读取成功!\n");
}
//3.插入
void Insert(struct stuInfo* head)
{
struct stuInfo* p, * t;
char pos[20] = { 0 };
t = (struct stuInfo*)malloc(sizeof(struct stuInfo));
t->next = 0;
p = head->next;
printf("请输入需要插入的信息:ID NAME SCORE:");
scanf("%s %s %f", t->id, t->name, &t->score);
printf("请输入插入位置(比如学号00005):");
scanf("%s", pos);
while (p)
{
if (strcmp(p->id, pos) == 0)
{
t->next = p->next;
p->next = t;
printf("插入成功!\n");
break;
}
else
p = p->next;
}
if (p == 0)
printf("未找到该位置,插入失败\n");
}
//根据成绩排序
void sortByScore(struct stuInfo* L)
{
struct stuInfo* p, * tail, * q;
tail = NULL;
while ((L->next->next) != tail)
{
p = L;
q = L->next;
while (q->next != tail)
{
if (q->score > q->next->score) //升序排列
{
p->next = q->next;
q->next = q->next->next;
p->next->next = q;
q = p->next;
}
q = q->next;
p = p->next;
}
tail = q;
}
}
//写文件
void writefile(struct stuInfo* head)
{
struct stuInfo* p = head->next;
FILE* fp = fopen("score.txt", "w");
while (p)
{
fprintf(fp, "%s %s %f\n", p->id, p->name, p->score);
p = p->next;
}
fclose(fp);
}
//显示链表
void showLinst(struct stuInfo* head)
{
struct stuInfo* p = head->next;
while (p)
{
printf("%s %s %f\n", p->id, p->name, p->score);
p = p->next;
}
}
int main()
{
struct stuInfo* head = 0;
int opt = 0;
//1.创建链表
head = CreateList();
//2.读文件
readFile(head);
//showLinst(head); //显示列表
//3.插入
Insert(head);
//4.排序
sortByScore(head);
//5.写文件
writefile(head);
showLinst(head); //显示列表
return 0;
}
可参考这个https://blog.csdn.net/technologist_37/article/details/118500579