创建一个动态链表,输入5位学生的数据(学号及姓名),遍历并输出链表中的数据。
时间: 2024-03-07 17:48:48 浏览: 16
好的,这是一个关于链表的问题。
首先,我们需要定义一个链表节点的结构体,包括学号和姓名两个成员变量,以及一个指向下一个节点的指针。
```c
struct student {
int id;
char name[20];
struct student *next;
};
```
然后,我们可以编写一个函数来动态创建链表。该函数需要循环5次,每次输入一个学生的学号和姓名,并将它们添加到链表的末尾。
```c
struct student *create_list() {
struct student *head = NULL;
struct student *prev = NULL;
// 循环5次,每次输入一个学生的学号和姓名,并将它们添加到链表的末尾
for (int i = 0; i < 5; i++) {
struct student *node = (struct student*)malloc(sizeof(struct student));
printf("请输入学生%d的学号:", i+1);
scanf("%d", &(node->id));
printf("请输入学生%d的姓名:", i+1);
scanf("%s", node->name);
node->next = NULL;
if (prev == NULL) {
head = node;
prev = node;
} else {
prev->next = node;
prev = node;
}
}
return head;
}
```
最后,我们可以编写一个遍历链表的函数,将链表中的每个节点的学号和姓名打印到控制台上。
```c
void traverse_list(struct student *head) {
printf("学号\t姓名\n");
while (head != NULL) {
printf("%d\t%s\n", head->id, head->name);
head = head->next;
}
}
```
完整代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
struct student {
int id;
char name[20];
struct student *next;
};
struct student *create_list() {
struct student *head = NULL;
struct student *prev = NULL;
// 循环5次,每次输入一个学生的学号和姓名,并将它们添加到链表的末尾
for (int i = 0; i < 5; i++) {
struct student *node = (struct student*)malloc(sizeof(struct student));
printf("请输入学生%d的学号:", i+1);
scanf("%d", &(node->id));
printf("请输入学生%d的姓名:", i+1);
scanf("%s", node->name);
node->next = NULL;
if (prev == NULL) {
head = node;
prev = node;
} else {
prev->next = node;
prev = node;
}
}
return head;
}
void traverse_list(struct student *head) {
printf("学号\t姓名\n");
while (head != NULL) {
printf("%d\t%s\n", head->id, head->name);
head = head->next;
}
}
int main() {
struct student *head = create_list();
traverse_list(head);
return 0;
}
```
当我们运行这段代码时,它将提示我们输入5个学生的学号和姓名,并将它们添加到链表中,然后遍历链表并将每个学生的学号和姓名打印到控制台上。