单向无头链表查找代码
时间: 2023-08-15 12:14:31 浏览: 61
当我们需要在单向无头链表中查找某个元素时,我们需要遍历整个链表,直到找到目标元素或者链表结束。下面是一个示例的单向无头链表查找代码:
```c++
#include <iostream>
// 定义链表节点结构
struct Node {
int data; // 节点数据
Node* next; // 指向下一个节点的指针
};
// 在链表尾部插入新节点
void insert(Node** head, int data) {
Node* newNode = new Node(); // 创建新节点
newNode->data = data;
newNode->next = nullptr;
if (*head == nullptr) {
*head = newNode;
} else {
Node* currNode = *head;
while (currNode->next != nullptr) {
currNode = currNode->next;
}
currNode->next = newNode;
}
}
// 在链表中查找目标元素
bool search(Node* head, int target) {
Node* currNode = head;
while (currNode != nullptr) {
if (currNode->data == target) {
return true;
}
currNode = currNode->next;
}
return false;
}
// 打印链表元素
void display(Node* head) {
Node* currNode = head;
while (currNode != nullptr) {
std::cout << currNode->data << " ";
currNode = currNode->next;
}
std::cout << std::endl;
}
int main() {
Node* head = nullptr;
// 插入节点
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
// 打印链表
display(head);
// 查找元素
int target = 3;
if (search(head, target)) {
std::cout << target << " found in the list." << std::endl;
} else {
std::cout << target << " not found in the list." << std::endl;
}
return 0;
}
```
在上面的代码中,我们定义了一个 `Node` 结构表示链表的节点,其中 `data` 存储节点的数据,`next` 指向下一个节点。`insert` 函数用于在链表尾部插入新节点。`search` 函数用于在链表中查找目标元素,并返回是否找到。`display` 函数用于打印链表的所有元素。
在 `main` 函数中,我们创建一个空链表,并插入一些节点。然后,我们调用 `display` 函数打印链表,再调用 `search` 函数查找目标元素是否存在。最后输出结果。
注意:这只是一个简单的示例代码,实际应用中可能需要处理更多的边界情况和错误处理。