(8分,用链表实现对单生成睛进行样储,插人及显示功能. 学生包括工D和score属性。 结构体类型定义如下 struct grade int score cher 10L61 struct grade *next 红)写函教创建单向链表并存储学生成绩信息,有入TD和soore按退号隔开,先给入score后输人加,当score《0时链来创建宽成.并输出创建后的链表信息. <2)写函数实现在第r个结点后面插人一个新结点,并输出插入 新结点后的销表信息。 3)写函教释放链表所占内存空目 在上函教依次调用各函效即可
时间: 2024-03-03 12:47:09 浏览: 18
以下是实现要求的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct grade {
int ID;
int score;
struct grade *next;
};
void create_list(struct grade **head) {
int id, score;
struct grade *new_node;
*head = NULL;
printf("Enter student ID and score (separated by space): ");
scanf("%d %d", &id, &score);
while (score >= 0) {
new_node = (struct grade*)malloc(sizeof(struct grade));
new_node->ID = id;
new_node->score = score;
new_node->next = *head;
*head = new_node;
printf("Enter student ID and score (separated by space): ");
scanf("%d %d", &id, &score);
}
}
void insert_node(struct grade **head, int pos) {
struct grade *new_node, *ptr;
int i;
ptr = *head;
for (i = 1; i < pos && ptr != NULL; i++) {
ptr = ptr->next;
}
if (ptr == NULL) {
printf("Cannot insert node at position %d\n", pos);
return;
}
printf("Enter student ID and score (separated by space): ");
new_node = (struct grade*)malloc(sizeof(struct grade));
scanf("%d %d", &new_node->ID, &new_node->score);
new_node->next = ptr->next;
ptr->next = new_node;
}
void display_list(struct grade *head) {
struct grade *ptr = head;
while (ptr != NULL) {
printf("ID: %d\tScore: %d\n", ptr->ID, ptr->score);
ptr = ptr->next;
}
}
void free_list(struct grade **head) {
struct grade *ptr = *head;
while (ptr != NULL) {
*head = (*head)->next;
free(ptr);
ptr = *head;
}
}
int main() {
struct grade *head = NULL;
int pos;
create_list(&head);
printf("Initial list:\n");
display_list(head);
printf("Enter position to insert new node: ");
scanf("%d", &pos);
insert_node(&head, pos);
printf("List after insertion:\n");
display_list(head);
free_list(&head);
return 0;
}
```
注:由于题目中没有规定 ID 的输入方式,所以这里采用了和 score 相同的方式,即在输入时用空格分隔。如果需要单独输入 ID,只需要稍作修改即可。