用c语言建立一个5个节点的学生(含4个分量)链表。
时间: 2024-03-17 13:46:09 浏览: 17
好的,以下是用C语言建立一个5个节点的学生链表的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student {
char name[20];
int age;
char gender;
float score;
struct student *next;
};
int main() {
struct student *head, *p;
head = (struct student *)malloc(sizeof(struct student));
head->next = NULL;
p = (struct student *)malloc(sizeof(struct student));
strcpy(p->name, "Tom");
p->age = 18;
p->gender = 'M';
p->score = 89.5;
p->next = NULL;
head->next = p;
p = (struct student *)malloc(sizeof(struct student));
strcpy(p->name, "Lucy");
p->age = 19;
p->gender = 'F';
p->score = 92.0;
p->next = NULL;
head->next->next = p;
p = (struct student *)malloc(sizeof(struct student));
strcpy(p->name, "John");
p->age = 20;
p->gender = 'M';
p->score = 87.5;
p->next = NULL;
head->next->next->next = p;
p = (struct student *)malloc(sizeof(struct student));
strcpy(p->name, "Mary");
p->age = 18;
p->gender = 'F';
p->score = 94.0;
p->next = NULL;
head->next->next->next->next = p;
p = (struct student *)malloc(sizeof(struct student));
strcpy(p->name, "David");
p->age = 19;
p->gender = 'M';
p->score = 85.5;
p->next = NULL;
head->next->next->next->next->next = p;
// 遍历链表并输出每个节点的信息
p = head->next;
while (p != NULL) {
printf("Name: %s, Age: %d, Gender: %c, Score: %.1f\n", p->name, p->age, p->gender, p->score);
p = p->next;
}
// 释放链表空间
p = head;
while (p != NULL) {
head = p->next;
free(p);
p = head;
}
return 0;
}
```
运行程序后,会输出每个节点的信息:
```
Name: Tom, Age: 18, Gender: M, Score: 89.5
Name: Lucy, Age: 19, Gender: F, Score: 92.0
Name: John, Age: 20, Gender: M, Score: 87.5
Name: Mary, Age: 18, Gender: F, Score: 94.0
Name: David, Age: 19, Gender: M, Score: 85.5
```
最后,别忘了释放链表空间,以免造成内存泄漏。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)