在模块入口点,创建链表以包含5个struct birthday元素。遍历链表并且输出内容到内
时间: 2023-11-01 20:03:26 浏览: 60
在模块入口点,我们可以创建一个包含5个 struct birthday 元素的链表。首先,我们需要定义 struct birthday 结构体,它包含年、月、日的日期信息。然后,我们可以使用指针创建链表并添加 5 个结构体元素。
struct birthday 结构体定义如下:
```
struct birthday {
int year;
int month;
int day;
};
```
我们可以使用以下代码创建链表并添加 5 个结构体元素:
```c
#include <stdio.h>
#include <stdlib.h>
struct birthday {
int year;
int month;
int day;
};
struct Node {
struct birthday data;
struct Node* next;
};
void traverseLinkedList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("Year: %d, Month: %d, Day: %d\n", current->data.year, current->data.month, current->data.day);
current = current->next;
}
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
struct Node* fourth = NULL;
struct Node* fifth = NULL;
// 分配内存并为结构体元素赋值
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
fourth = (struct Node*)malloc(sizeof(struct Node));
fifth = (struct Node*)malloc(sizeof(struct Node));
// 设置结构体元素的值
head->data.year = 1990;
head->data.month = 1;
head->data.day = 1;
head->next = second;
second->data.year = 1995;
second->data.month = 2;
second->data.day = 2;
second->next = third;
third->data.year = 2000;
third->data.month = 3;
third->data.day = 3;
third->next = fourth;
fourth->data.year = 2005;
fourth->data.month = 4;
fourth->data.day = 4;
fourth->next = fifth;
fifth->data.year = 2010;
fifth->data.month = 5;
fifth->data.day = 5;
fifth->next = NULL;
// 遍历链表并输出内容
traverseLinkedList(head);
// 释放内存
free(head);
free(second);
free(third);
free(fourth);
free(fifth);
return 0;
}
```
以上代码会创建一个链表,包含 5 个 struct birthday 元素,并输出每个元素的日期信息。输出的结果如下:
```
Year: 1990, Month: 1, Day: 1
Year: 1995, Month: 2, Day: 2
Year: 2000, Month: 3, Day: 3
Year: 2005, Month: 4, Day: 4
Year: 2010, Month: 5, Day: 5
```
最后,记得释放链表所占用的内存空间,避免内存泄漏。