用c语言创建一个有2022个节点的(无序)链 表,链表每个结点存放的数据为 11922,20251之问的日期(年、月、日) 数据(随机产生)
时间: 2023-04-06 12:02:55 浏览: 47
好的,这个问题我可以回答。以下是用 C 语言创建一个有 2022 个节点的无序链表,每个节点存放的数据为 2022 年 1 月 1 日至 2024 年 12 月 31 日之间的随机日期和数据的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义链表节点结构体
struct Node {
int year;
int month;
int day;
int data;
struct Node* next;
};
int main() {
// 初始化随机数种子
srand(time(NULL));
// 创建链表头节点
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
head->next = NULL;
// 创建 2022 个节点并插入链表
for (int i = 0; i < 2022; i++) {
// 生成随机日期和数据
int year = rand() % 3 + 2022; // 2022-2024 年
int month = rand() % 12 + 1; // 1-12 月
int day = rand() % 31 + 1; // 1-31 日
int data = rand() % 10000; // 0-9999 的随机数
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->year = year;
newNode->month = month;
newNode->day = day;
newNode->data = data;
// 将新节点插入链表头部
newNode->next = head->next;
head->next = newNode;
}
// 遍历链表并输出每个节点的数据
struct Node* p = head->next;
while (p != NULL) {
printf("%d-%02d-%02d: %d\n", p->year, p->month, p->day, p->data);
p = p->next;
}
// 释放链表内存
p = head;
while (p != NULL) {
struct Node* temp = p;
p = p->next;
free(temp);
}
return 0;
}
```
希望这个回答能够帮到你!