用c语言写一个单链表储存学生的学号和成绩
时间: 2023-04-06 15:04:35 浏览: 121
好的,这个问题可以回答。以下是用C语言实现单链表储存学生学号和成绩的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct student {
int id;
int score;
struct student *next;
};
int main() {
struct student *head = NULL;
struct student *tail = NULL;
int id, score;
// 读入学生信息并创建链表
while (scanf("%d%d", &id, &score) == 2) {
struct student *node = (struct student*) malloc(sizeof(struct student));
node->id = id;
node->score = score;
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
// 遍历链表并输出学生信息
struct student *p = head;
while (p != NULL) {
printf("id: %d, score: %d\n", p->id, p->score);
p = p->next;
}
// 释放链表内存
p = head;
while (p != NULL) {
struct student *tmp = p;
p = p->next;
free(tmp);
}
return 0;
}
```
以上代码实现了读入学生信息并创建单链表,遍历链表并输出学生信息,最后释放链表内存的功能。
阅读全文