帮我写一个C语言的简单链表
时间: 2023-03-28 07:00:45 浏览: 56
好的,我可以帮您写一个简单的C语言链表。链表是一种常见的数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的指针。以下是一个简单的链表示例:
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
int main() {
struct node *head = NULL;
struct node *current = NULL;
struct node *new_node = NULL;
// 创建第一个节点
head = (struct node*)malloc(sizeof(struct node));
head->data = 1;
head->next = NULL;
current = head;
// 创建第二个节点
new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = 2;
new_node->next = NULL;
current->next = new_node;
current = new_node;
// 创建第三个节点
new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = 3;
new_node->next = NULL;
current->next = new_node;
current = new_node;
// 遍历链表并输出节点的值
current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
// 释放内存
current = head;
while (current != NULL) {
new_node = current->next;
free(current);
current = new_node;
}
return ;
}
```
这个程序创建了一个包含三个节点的链表,并输出了每个节点的值。您可以根据需要修改节点的数量和值。请注意,在使用完链表后,需要释放每个节点的内存以避免内存泄漏。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)