以下是创建动态链表并输出该链表的 C 程序:
``` #include <stdio.h> #include <stdlib.h>
// 定义学生结构体 struct Student { int num; char name[20]; float score[3]; struct Student *next; };
int main(void) { struct Student *head = NULL; // 定义头指针 struct Student *p, *q; // p 指向新节点,q 指向尾节点 int num; char name[20]; float score[3];
// 读入学生信息,当 num 为 0 时停止读入 printf("请输入学生信息(格式:num, name, score1, score2, score3):\n"); while (1) { scanf("%d, %s, %f, %f, %f", &num, name, &score[0], &score[1], &score[2]); if (num == 0) { break; }
// 分配内存空间p = (struct Student*)malloc(sizeof(struct Student));
if (p == NULL) {
printf("内存分配失败\n");
return 1;
}
// 填充学生信息
p->num = num;
for (int i = 0; i < 20; i++) {
p->name[i] = name[i];
}
for (int i = 0; i < 3; i++) {
p->score[i] = score[i];
}
p->next = NULL; // 新节点的 next 指针指向 NULL
// 将新节点插入链表
if (head == NULL) { // 如果是第一个节点,则设为头指针
head = p;
} else { // 如果不是第一个节点,则将新节点插入到尾节点的后面
q->next = p;
}
q = p; // 更新尾节点
}
// 遍历链表并输出学生信息 printf("学生信