用c语言为5个学生信息建立动态链表,每个学生包括学号、姓名和分数 3种信息(要求这些信息能从文件中导入),输入一个学号值删除列表中该学号的学生节点。
时间: 2024-05-12 08:21:16 浏览: 77
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
struct student {
int num;
char name[20];
int score;
struct student *next;
};
// 从文件中读取学生信息并创建链表
struct student *create_list(void) {
struct student *head, *p, *tail;
head = (struct student *)malloc(sizeof(struct student));
tail = head;
FILE *fp;
fp = fopen("students.txt", "r");
if (fp == NULL) {
printf("Cannot open file!\n");
exit(1);
}
while (!feof(fp)) {
p = (struct student *)malloc(sizeof(struct student));
fscanf(fp, "%d %s %d", &p->num, p->name, &p->score);
p->next = NULL;
tail->next = p;
tail = p;
}
fclose(fp);
return head;
}
// 遍历链表,并打印出每个学生的信息
void print_list(struct student *head) {
struct student *p = head->next;
while (p != NULL) {
printf("%d %s %d\n", p->num, p->name, p->score);
p = p->next;
}
}
// 删除学号为num的学生节点
void delete_node(struct student *head, int num) {
struct student *p = head->next;
struct student *prev = head;
while (p != NULL) {
if (p->num == num) {
prev->next = p->next;
free(p);
printf("Student %d has been deleted!\n", num);
return;
}
prev = p;
p = p->next;
}
printf("Student %d not found!\n", num);
}
int main() {
struct student *head = create_list();
printf("Original list:\n");
print_list(head);
int num;
printf("Please enter the student number you want to delete: ");
scanf("%d", &num);
delete_node(head, num);
printf("New list:\n");
print_list(head);
return 0;
}
```
阅读全文