C语言中输出链表的偶数节点121


链表是一种广泛应用的数据结构,用于存储线性数据。它由一组节点组成,每个节点包含数据和指向下一个节点的指针。在某些情况下,需要从链表中提取特定类型的节点,例如偶数节点。

C语言提供了一种简洁高效的方法来输出链表中的偶数节点。以下是实现此操作的步骤:

算法1. 遍历链表:从链表的头节点开始,逐个遍历所有节点。
2. 检查节点值:对于每个节点,检查其数据值是否为偶数(即是否能被2整除)。
3. 打印偶数节点:如果节点值是偶数,将其打印到屏幕上。

代码实现以下代码展示了如何使用C语言输出链表中的偶数节点:
```c
#include
#include
// 节点结构
struct Node {
int data;
struct Node *next;
};
// 输出链表中的偶数节点
void printEvenNodes(struct Node *head) {
while (head != NULL) {
// 检查节点值是否为偶数
if (head->data % 2 == 0) {
printf("%d ", head->data); // 打印偶数节点
}
head = head->next; // 移动到下一个节点
}
}
// 主函数
int main() {
// 创建一个链表
struct Node *head = NULL;
struct Node *second = NULL;
struct Node *third = NULL;
struct Node *fourth = NULL;
// 分配内存并初始化节点
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
fourth = (struct Node *)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = fourth;
fourth->data = 4;
fourth->next = NULL;
// 输出链表中的偶数节点
printEvenNodes(head);
return 0;
}
```

示例输出对于输入链表 `1 -> 2 -> 3 -> 4`,输出将是:
```
2 4
```

通过遵循本文中描述的步骤,您可以编写一个高效的C语言程序来输出链表中的偶数节点。该算法的时间复杂度为O(n),其中n是链表中的节点数。

2024-11-19


上一篇:C语言字符和数字输出

下一篇:用 C 语言绘制猫咪图形