如何使用c语言输出学习小组的链表,每人一个结点,结点中有四个成员:姓名,出生年,出生月,指针。链表中生日大者在前,小者在后。输出该链表
时间: 2024-05-09 22:17:19 浏览: 8
以下是一个参考代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义学生结构体
typedef struct Student {
char name[20]; // 姓名
int birth_year; // 出生年
int birth_month; // 出生月
struct Student *next; // 指向下一个结点的指针
} Student;
// 在链表中插入新结点,按生日从早到晚排序
void insert_node(Student **head, Student *new_node) {
if (*head == NULL) { // 链表为空,直接插入
*head = new_node;
return;
}
// 找到合适的位置插入
Student *cur = *head;
Student *prev = NULL;
while (cur != NULL) {
if (new_node->birth_year < cur->birth_year ||
(new_node->birth_year == cur->birth_year && new_node->birth_month < cur->birth_month)) {
break;
}
prev = cur;
cur = cur->next;
}
if (prev == NULL) { // 插入到链表头部
new_node->next = *head;
*head = new_node;
} else { // 插入到链表中间或尾部
new_node->next = cur;
prev->next = new_node;
}
}
// 创建新结点
Student *create_node(char *name, int birth_year, int birth_month) {
Student *new_node = (Student *)malloc(sizeof(Student));
strcpy(new_node->name, name);
new_node->birth_year = birth_year;
new_node->birth_month = birth_month;
new_node->next = NULL;
return new_node;
}
// 输出链表
void print_list(Student *head) {
printf("学习小组成员:\n");
while (head != NULL) {
printf("%s %d年%d月\n", head->name, head->birth_year, head->birth_month);
head = head->next;
}
}
int main() {
// 创建示例链表
Student *head = NULL;
insert_node(&head, create_node("张三", 2000, 1));
insert_node(&head, create_node("李四", 1999, 5));
insert_node(&head, create_node("王五", 2001, 8));
insert_node(&head, create_node("赵六", 2000, 3));
insert_node(&head, create_node("钱七", 2001, 2));
// 输出链表
print_list(head);
// 释放链表内存
Student *cur = head;
while (cur != NULL) {
Student *next = cur->next;
free(cur);
cur = next;
}
return 0;
}
```
输出结果:
```
学习小组成员:
李四 1999年5月
张三 2000年1月
赵六 2000年3月
钱七 2001年2月
王五 2001年8月
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)