思维导图
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 定义学生结构体
typedef struct Student {
char name;
int age;
float score;
struct Student *next;
} Student;
// 创建新节点
Student* createStudent( char* name, int age, float score)
{
Student* H = (Student*)malloc(sizeof(Student));
if(H == NULL)
{
perror("错误\n");
return NULL;
}
strcpy(H->name, name);
H->age = age;
H->score = score;
H->next = NULL;
return H;
}
// 向链表添加学生
void addStudent(Student* head, char* name, int age, float score) {
Student* newStudent = createStudent(name, age, score);
if () {
*head = newStudent;
} else {
Student* current = *head;
while (current->next) {
current = current->next;
}
current->next = newStudent;
}
}
// 保存链表到文件
void save( Student* head, char* filename)
{
FILE* wfp = fopen(filename, "w");
if (wfp == NULL)
{
printf("错误\n");
return 1;
}
Student* current = head;
while (current) {
fprintf(file, "%s,%d,%f\n", current->name, current->age, current->score);
current = current->next;
}
fclose(file);
}
// 从文件加载学生到链表
void load(Student* head, char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("错误\n");
return ;
}
char name;
int age;
float score;
while (fscanf(file, "%[^,],%d,%f\n", name, &age, &score) != EOF) {
addStudent(head, name, age, score);
}
fclose(file);
}
// 显示链表内容
void display(const Student* head) {
const Student* current = head;
while (current) {
printf("Name: %s, Age: %d, Score: %.2f\n", current->name, current->age, current->score);
current = current->next;
}
}
// 释放链表内存
void freeStudents(Student* head) {
Student* current = head;
while (current) {
Student* next = current->next;
free(current);
current = next;
}
}
int main()
{
Student* head = NULL;
addStudent(&head, "张三", 20, 85.5);
addStudent(&head, "李四", 21, 92.0);
addStudent(&head, "王五", 19, 78.0);
return 0;
}