利用 C 语言遍历和输出链表56


链表是一种线性数据结构,其中每个元素由一个值和指向下一个元素的指针组成。在 C 语言中,链表可以用结构体和指针来表示。本文将介绍如何创建、遍历和输出链表。

创建链表

要创建链表,需要定义一个结构体来存储元素的值和指向下一个元素的指针。然后,可以动态分配链表节点,并使用指针将它们连接起来。```c
struct node {
int data;
struct node *next;
};
struct node *head = NULL; // 头指针
```

遍历链表

要遍历链表,需要使用一个指针从头节点开始,并逐个访问每个节点。当指针指向 NULL 时,表示链表已遍历结束。```c
struct node *current = head;
while (current != NULL) {
// 访问节点数据
printf("%d", current->data);
// 移动到下一个节点
current = current->next;
}
```

输出链表

要输出链表,可以在遍历链表的同时打印每个节点的值。```c
struct node *current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL");
```

完整示例

以下是创建、遍历和输出链表的完整示例:```c
#include
#include
struct node {
int data;
struct node *next;
};
struct node *head = NULL; // 头指针
int main() {
// 创建链表
struct node *node1 = malloc(sizeof(struct node));
node1->data = 10;
node1->next = NULL;
head = node1;
struct node *node2 = malloc(sizeof(struct node));
node2->data = 20;
node2->next = NULL;
node1->next = node2;
struct node *node3 = malloc(sizeof(struct node));
node3->data = 30;
node3->next = NULL;
node2->next = node3;
// 遍历链表
struct node *current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL");
return 0;
}
```

其他注意事项

在使用链表时,还需要考虑以下注意事项:* 内存管理:链表中的每个节点都是动态分配的,因此需要在不再需要时释放它们以避免内存泄漏。
* 循环引用:如果链表中的一个节点指向它自己或另一个节点,将形成循环引用,导致程序崩溃。
* 链表操作的复杂度:插入或删除链表中的节点的复杂度为 O(1),但查找节点的复杂度为 O(n),其中 n 是链表中的节点数。

2024-10-23


上一篇:C 语言链表输出

下一篇:C 语言函数式编程范例