用c语言为5个学生信息建立动态链表,每个学生包括 学号、姓名和分数 3种信息(要求这些信息能 从文件中导入),输入一个学号值删除列表中 该学号的学生节点。
时间: 2023-05-15 13:04:51 浏览: 129
C语言——建立一个链表表示学生的信息(学号、姓名、分数)
4星 · 用户满意度95%
好的,这是一个关于动态链表的编程问题。以下是一个示例代码,可以实现你所描述的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
typedef struct student {
int id;
char name[20];
int score;
struct student *next;
} Student;
// 从文件中读取学生信息并创建链表
Student *createListFromFile(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file %s\n", filename);
return NULL;
}
Student *head = NULL;
Student *tail = NULL;
while (!feof(fp)) {
Student *s = (Student *)malloc(sizeof(Student));
fscanf(fp, "%d %s %d", &(s->id), s->name, &(s->score));
s->next = NULL;
if (head == NULL) {
head = s;
tail = s;
} else {
tail->next = s;
tail = s;
}
}
fclose(fp);
return head;
}
// 根据学号删除节点
Student *deleteNodeById(Student *head, int id) {
Student *prev = NULL;
Student *curr = head;
while (curr != NULL) {
if (curr->id == id) {
if (prev == NULL) {
head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
printf("Student with ID %d has been deleted.\n", id);
return head;
}
prev = curr;
curr = curr->next;
}
printf("Student with ID %d not found.\n", id);
return head;
}
// 打印链表中的所有学生信息
void printList(Student *head) {
Student *curr = head;
while (curr != NULL) {
printf("%d %s %d\n", curr->id, curr->name, curr->score);
curr = curr->next;
}
}
int main() {
// 从文件中创建链表
Student *head = createListFromFile("students.txt");
if (head == NULL) {
return 1;
}
// 打印链表中的所有学生信息
printf("Original list:\n");
printList(head);
// 删除学号为 1002 的学生节点
head = deleteNodeById(head, 1002);
// 打印删除后的链表
printf("List after deletion:\n");
printList(head);
return 0;
}
```
注意:这只是一个示例代码,实际应用中可能需要根据具体需求进行修改。
阅读全文