为5个学生信息建立动态链表,每个学生包括 学号、姓名和分数3种信息(要求这些信息能 从文件中导入),输入一个学号值删除列表中 该学号的学生节点。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 20 // 学号、姓名的最大长度
// 学生信息结构体
struct student {
char id[MAX_LEN];
char name[MAX_LEN];
int score;
struct student *next;
};
// 从文件中读取学生信息并创建链表
struct student* read_students(const char* filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file %s\n", filename);
return NULL;
}
struct student *head = NULL, *tail = NULL;
// 逐行读取文件内容,每行对应一个学生信息
char line[MAX_LEN * 3 + 5];
while (fgets(line, MAX_LEN * 3 + 5, fp) != NULL) {
// 将一行内容拆分成学号、姓名和分数3个字段
char id[MAX_LEN], name[MAX_LEN];
int score;
sscanf(line, "%s %s %d", id, name, &score);
// 创建新节点并插入到链表尾部
struct student *node = (struct student*) malloc(sizeof(struct student));
strcpy(node->id, id);
strcpy(node->name, name);
node->score = score;
node->next = NULL;
if (head == NULL) {
head = node;
} else {
tail->next = node;
}
tail = node;
}
fclose(fp);
return head;
}
// 打印链表中的所有学生信息
void print_students(struct student *head) {
printf("%-10s%-10s%-10s\n", "ID", "Name", "Score");
printf("-----------------------------------\n");
for (struct student *p = head; p != NULL; p = p->next) {
printf("%-10s%-10s%-10d\n", p->id, p->name, p->score);
}
}
// 在链表尾部插入新的学生信息
struct student* insert_student(struct student *head, const char *id, const char *name, int score) {
// 创建新节点并插入到链表尾部
struct student *node = (struct student*) malloc(sizeof(struct student));
strcpy(node->id, id);
strcpy(node->name, name);
node->score = score;
node->next = NULL;
if (head == NULL) {
head = node;
} else {
struct student *p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
}
return head;
}
// 删除学号为指定值的学生信息
struct student* delete_student(struct student *head, const char *id) {
if (head == NULL) {
return NULL;
}
struct student *prev = NULL, *p = head;
while (p != NULL) {
if (strcmp(p->id, id)==0)
{
prev->next = p->next;
free(p);
}
else
{
prev = prev->next;
p = prev->next;
}
}
return head;
}
50 5
结尾无空行