用C语言创建链表并随时间增加链表个数
时间: 2023-05-25 11:01:46 浏览: 103
c语言链表创建
A:可以使用以下C语言代码创建一个基本的链表数据结构,并在随着时间的增加,动态地增加链表的个数:
```c
#include <stdio.h>
#include <stdlib.h>
//定义链表结构
struct node {
int data;
struct node* next;
};
//创建链表
struct node* create_list() {
struct node* head = NULL;
head = (struct node*)malloc(sizeof(struct node));
if (head == NULL) {
printf("Error! Memory not allocated.");
exit(0);
}
head->data = 0;
head->next = NULL;
return head;
}
//插入链表节点
void insert_node(struct node* head, int data) {
struct node* new = NULL;
new = (struct node*)malloc(sizeof(struct node));
new->data = data;
new->next = NULL;
struct node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = new;
}
//打印链表
void print_list(struct node* head) {
struct node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int main() {
//创建链表
struct node* head = create_list();
//插入节点
insert_node(head, 1);
insert_node(head, 2);
insert_node(head, 3);
//打印链表
printf("List 1:\n");
print_list(head);
//创建第二个链表
struct node* head2 = create_list();
//插入节点
insert_node(head2, 4);
insert_node(head2, 5);
insert_node(head2, 6);
//打印链表
printf("List 2:\n");
print_list(head2);
//释放内存
free(head);
free(head2);
return 0;
}
```
运行结果:
```
List 1:
0 -> 1 -> 2 -> 3 -> NULL
List 2:
0 -> 4 -> 5 -> 6 -> NULL
```
阅读全文