使用链表建立一个学生信息链表,C语言
时间: 2023-04-04 22:04:19 浏览: 78
可以使用结构体来表示学生信息,例如:
struct Student {
char name[20];
int age;
float score;
struct Student *next;
};
然后可以使用指针来动态地创建链表,例如:
struct Student *head = NULL;
struct Student *p = NULL;
// 创建第一个节点
head = (struct Student*)malloc(sizeof(struct Student));
strcpy(head->name, "张三");
head->age = 20;
head->score = 90.0;
head->next = NULL;
// 创建第二个节点
p = (struct Student*)malloc(sizeof(struct Student));
strcpy(p->name, "李四");
p->age = 21;
p->score = 85.0;
p->next = NULL;
head->next = p;
// 创建第三个节点
p = (struct Student*)malloc(sizeof(struct Student));
strcpy(p->name, "王五");
p->age = 22;
p->score = 95.0;
p->next = NULL;
head->next->next = p;
// 遍历链表并输出每个节点的信息
p = head;
while (p != NULL) {
printf("姓名:%s,年龄:%d,成绩:%.1f\n", p->name, p->age, p->score);
p = p->next;
}
注意要在程序结束时释放动态分配的内存,例如:
p = head;
while (p != NULL) {
head = head->next;
free(p);
p = head;
}