c语言每过一秒添加一个链表
时间: 2023-05-22 10:03:13 浏览: 86
C语言中关于链表
可以通过使用定时器函数和链表操作实现每过一秒添加一个节点到链表中。具体实现可参考下列代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct Node
{
int data;
struct Node *next;
};
void addNode(struct Node **head_ref, int new_data)
{
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
void printList(struct Node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
void addNodeAfterDelay(struct Node **head_ref, int data, int delay)
{
time_t start_t, current_t;
int elapsed_time = 0;
time(&start_t);
while (elapsed_time < delay)
{
time(¤t_t);
elapsed_time = (int) difftime(current_t, start_t);
}
addNode(head_ref, data);
}
int main()
{
struct Node *head = NULL;
int i;
for (i = 0; i < 10; i++)
{
addNodeAfterDelay(&head, i, 1);
printList(head);
printf("\n");
}
return 0;
}
```
以上代码实现了将数字 0 到 9 分别添加到链表中,每隔一秒钟添加一个数字。
阅读全文