前言
在写学生成绩分析时,会给学生一个排名,但一般成绩录入时,都是无序的,如果我们用链表存储信息,那么构造的数据结构中肯定还有其他的信息,如姓名,学号等,所以我们得根据成绩进行链表节点的交换。1. 从文件中读取信息并存入链表中
在这周写系统时,首先遇见了从文件中读取的数据是乱码的问题,如果是用xcode进行操作时,解决方法有以下两种。
- 首先可以将右边的text encoding 改为utf - 16。如下图所示

- 如果读取的汉字还是乱码,原因可能是txt文件是在Windows环境下创建的,我们可以将文件内容复制,在macos下重新创建txt文件即可解决。
下面是从文件读取信息存入链表的步骤
1.首先根据系统需求设计结构体
struct student { // 学生数据结构
char name[20];
char id[20];
char classnum[20];
int score1;
int score2;
int score3;
struct student *next;
};
2.创建链表,这里是用头插法创建链表,利用fscanf函数将数据存入链表
struct student *create(char name[]) { // 从文件中读取所有学生的信息并用链表存储,参数为路径
FILE *fp = fopen(name, "r");
if (fp == NULL) {
printf("不存在文件%s\n", name);
exit(1);
}
struct student *head = (struct student*)malloc(sizeof(struct student));
head->next = NULL;
while (!(feof(fp))) {
struct student *p = (struct student*)malloc(sizeof(struct student));
fscanf(fp, "%s %s %s %d %d %d\n", p->name, p->id, p->classnum, &p->score1, &p->score2, &p->score3);
p->next = head->next;
head->next = p;
}
return head;
}
代码中的参数为文件的路径。
对链表进行排序
在这里我对链表的排序方法是插入排序,以某个数据为判断标准,寻找结点合适的位置插入。
代码如下:
struct student *sort(struct student *head) { //语文成绩
if (head == NULL) {
return head;
}
struct student *dummyHead = (struct student*)malloc(sizeof(struct student));
dummyHead->score1 = 0;
dummyHead = head;
struct student *ans = head->next;
struct student *curr = head->next->next;
while (curr != NULL) {
if (ans->score1 >= curr->score1) {
ans = ans->next;
} else {
struct student *prev = dummyHead;
while (prev->next->score1 >= curr->score1) {
prev = prev->next;
}
ans->next = curr->next;
curr->next = prev->next;
prev->next = curr;
}
curr = ans->next;
}
return dummyHead;
}
指针ans为排好序的链表的最后一个结点,curr为待排序结点,如果curr中的成绩小于ans中的成绩,此时不用交换,令ans向后一个结点,如果大于的话,从链表的头结点开始给curr寻找相对应的位置,直到遍历链表的每一个结点。
版权声明:本文为chabuduoxs原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。