建立一个描述学生成绩的无序链表,各结点内容如表8.3所示。计算各学生的总成绩,并输出链表中各学生结点的信息内容。最后删除链表,收回链表占用的存储空间。建立无序链表、计算总成绩、输出链表、删除链表各用一个函数实现。在主函数中调用四个函数完成上述操作。
时间: 2024-03-13 08:18:07 浏览: 40
好的,我了解你的要求,下面是我对你的问题的回答:
建立一个描述学生成绩的无序链表,各结点内容如表8.3所示。计算各学生的总成绩,并输出链表中各学生结点的信息内容。最后删除链表,收回链表占用的存储空间。建立无序链表、计算总成绩、输出链表、删除链表各用一个函数实现。在主函数中调用四个函数完成上述操作。
下面是代码实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
typedef struct student {
char name[MAX_NAME_LEN];
int chinese_grade;
int math_grade;
int english_grade;
int total_grade;
struct student *next;
} Student;
int calc_total_grade(Student *head) {
int total = 0;
Student *cur = head->next;
while (cur != NULL) {
cur->total_grade = cur->chinese_grade + cur->math_grade + cur->english_grade;
total += cur->total_grade;
cur = cur->next;
}
return total;
}
void print_student_list(Student *head) {
printf("姓名\t语文\t数学\t英语\t总分\n");
Student *cur = head->next;
while (cur != NULL) {
printf("%s\t%d\t%d\t%d\t%d\n", cur->name, cur->chinese_grade, cur->math_grade, cur->english_grade, cur->total_grade);
cur = cur->next;
}
}
void delete_student_list(Student *head) {
Student *cur = head->next;
while (cur != NULL) {
Student *next = cur->next;
free(cur);
cur = next;
}
head->next = NULL;
}
void create_student_list(Student *head) {
Student *cur = head;
while (1) {
printf("请输入学生姓名(输入 n 结束):");
char name[MAX_NAME_LEN];
scanf("%s", name);
if (strcmp(name, "n") == 0) {
break;
}
Student *new_student = (Student *) malloc(sizeof(Student));
strcpy(new_student->name, name);
printf("请输入 %s 的语文成绩:", name);
scanf("%d", &new_student->chinese_grade);
printf("请输入 %s 的数学成绩:", name);
scanf("%d", &new_student->math_grade);
printf("请输入 %s 的英语成绩:", name);
scanf("%d", &new_student->english_grade);
new_student->next = NULL;
cur->next = new_student;
cur = cur->next;
}
}
int main() {
Student *head = (Student *) malloc(sizeof(Student));
head->next = NULL;
create_student_list(head);
printf("总成绩为:%d\n", calc_total_grade(head));
print_student_list(head);
delete_student_list(head);
free(head);
return 0;
}
```
上面的代码实现了建立描述学生成绩的无序链表、计算每个学生的总成绩、输出链表中各学生结点的信息内容、删除链表以及收回链表占用的存储空间。在主函数中依次调用了这四个函数,完成了上述操作。