c语言遍历可不断添加的单链表中含有指定数据的元素,并打印
时间: 2024-03-15 21:45:41 浏览: 21
好的,这里提供一份 C 语言的代码,实现了遍历可不断添加的单链表中含有指定数据的元素,并将符合条件的元素打印出来:
```c
#include <stdio.h>
#include <stdlib.h>
// 链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 在链表头部插入新节点
void insertAtBeginning(struct Node** head, int data) {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = *head;
*head = new_node;
}
// 遍历链表,打印含有指定数据的节点
void printNodes(struct Node* head, int target) {
struct Node* current = head;
int count = 0;
while (current != NULL) {
if (current->data == target) {
printf("Node %d contains the target value %d.\n", count, target);
}
current = current->next;
count++;
}
}
int main() {
// 创建链表
struct Node* head = NULL;
// 在链表头部插入新节点
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtBeginning(&head, 1);
insertAtBeginning(&head, 2);
// 遍历链表并打印
printNodes(head, 2);
return 0;
}
```
在这个代码中,我们定义了一个可以不断添加元素的单链表。通过 `insertAtBeginning` 函数,在链表头部插入新的节点。接着,我们定义了 `printNodes` 函数,用于遍历链表并打印含有指定数据的节点。
在 `main` 函数中,我们创建了一个含有四个节点的链表,并使用 `insertAtBeginning` 函数向其中插入元素。最后,我们调用 `printNodes` 函数,打印出链表中所有值为 2 的节点。
运行上述代码,输出结果如下:
```
Node 0 contains the target value 2.
Node 3 contains the target value 2.
```
这表示链表中第一个和第四个节点都包含值为 2 的数据。