用C语言实现链表每秒增加一个节点
时间: 2024-05-03 11:23:10 浏览: 11
这里是一个简单的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct node {
int data;
struct node *next;
} Node;
int main() {
srand(time(NULL)); // 初始化随机数生成器
Node *head = NULL, *tail = NULL;
int count = 0;
while (1) {
// 每秒增加一个节点
sleep(1);
// 创建新节点
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->data = rand() % 100; // 生成随机数
new_node->next = NULL;
// 插入节点
if (head == NULL) {
head = new_node;
tail = new_node;
} else {
tail->next = new_node;
tail = new_node;
}
// 打印链表
printf("Count: %d, List: ", ++count);
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
return 0;
}
```
代码使用了 `sleep()` 函数来等待一秒钟,然后生成一个新的节点插入到链表中,并打印链表。循环会一直执行下去,直到程序被手动停止。