链表是一种基本的数据结构,它由节点组成,每个节点包含两部分:数据和指向下一个节点的指针。C 语言中使用指针来实现链表。链表的优势在于其动态的特性,允许在运行时动态地分配内存来存储数据。
下面是一个简单的单向链表的例子:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
int main() {
// 定义链表的头指针
struct Node *head = NULL;
// 创建节点并添加数据
struct Node *node1 = (struct Node *)malloc(sizeof(struct Node));
node1->data = 1;
node1->next = NULL;
head = node1; // 将第一个节点作为链表头
struct Node *node2 = (struct Node *)malloc(sizeof(struct Node));
node2->data = 2;
node2->next = NULL;
node1->next = node2; // 将第二个节点连接到第一个节点的后面
struct Node *node3 = (struct Node *)malloc(sizeof(struct Node));
node3->data = 3;
node3->next = NULL;
node2->next = node3; // 将第三个节点连接到第二个节点的后面
// 遍历链表并打印节点数据
struct Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
// 释放节点的内存
current = head;
while (current != NULL) {
struct Node *temp = current;
current = current->next;
free(temp);
}
return 0;
}
这个例子创建了一个包含三个节点的单向链表,每个节点存储一个整数。它首先分配内存来创建节点,然后通过指针连接这些节点以形成链表。随后,它遍历链表并打印每个节点的数据,并最终释放节点的内存。
要点:
- 链表由节点组成,每个节点包含数据和指向下一个节点的指针。
- 链表的头指针指向第一个节点,通过节点之间的指针连接形成链表。
- 使用
malloc()
分配节点的内存,并使用free()
释放内存以避免内存泄漏。 - 遍历链表时,通过指针按顺序访问节点,并执行相应的操作。
这只是链表的基础概念和实现示例。在实际应用中,链表可用于实现更复杂的数据结构和算法,并且有多种类型的链表(单向链表、双向链表、循环链表等)适用于不同的需求。
csdn原创者:爱睡的梨
-文章会不断的更新,希望能够帮助到需要的人