在定义学生结构体struct Student类型如下: char id[10]; //学号 char Name[20];//姓名 double Score[3];//3门课程成绩的基础上,增加struct Student* next成员。并以新的学生结构体struct Student类型为结点,使用malloc函数动态建立单链表。程序结束前使用free函数释放单链表所有结点。用c语言编写且有主函数。
时间: 2024-02-13 18:01:22 浏览: 25
好的,以下是实现这个功能的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
struct Student {
char id[10]; // 学号
char Name[20]; // 姓名
double Score[3]; // 3门课程成绩
struct Student* next; // 指向下一个结点的指针
};
int main() {
// 创建头结点
struct Student* head = (struct Student*)malloc(sizeof(struct Student));
head->next = NULL;
// 循环添加新结点
while (1) {
// 创建新结点
struct Student* new_node = (struct Student*)malloc(sizeof(struct Student));
new_node->next = NULL;
// 输入学生信息
printf("请输入学生学号:");
scanf("%s", new_node->id);
if (strcmp(new_node->id, "exit") == 0) {
// 如果输入exit,则退出输入循环
free(new_node);
break;
}
printf("请输入学生姓名:");
scanf("%s", new_node->Name);
printf("请输入学生三门课程的成绩:");
scanf("%lf %lf %lf", &new_node->Score[0], &new_node->Score[1], &new_node->Score[2]);
// 将新结点插入到链表尾部
struct Student* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = new_node;
}
// 遍历链表并输出学生信息
printf("学生信息如下:\n");
struct Student* p = head->next;
while (p != NULL) {
printf("学号:%s,姓名:%s,三门课程成绩:%.2f %.2f %.2f\n", p->id, p->Name, p->Score[0], p->Score[1], p->Score[2]);
p = p->next;
}
// 释放链表内存
p = head->next;
while (p != NULL) {
struct Student* next = p->next;
free(p);
p = next;
}
free(head);
return 0;
}
```
这个程序会动态地建立一个单链表,每个结点存储一个学生的学号、姓名和三门课程的成绩,并使用malloc函数分配内存。程序结束前,使用free函数释放所有结点的内存。