建立单链表,对单链表实现功能查询,找到了打印"yes",否则打印“no”,输入时,第一行为线性表元素个数,第二行为线性表元素,第三行为要查找的值,用c++实现
时间: 2024-11-20 14:42:44 浏览: 17
在C++中,我们可以创建一个简单的单链表结构,并实现一个函数来检查目标值是否存在于链表中。以下是基本的步骤:
```cpp
#include <iostream>
using namespace std;
// 定义链表节点结构
struct Node {
int data;
Node* next;
};
// 创建链表头结点
Node* createList(int n) {
Node* head = new Node();
Node* tail = head;
for (int i = 0; i < n; ++i) {
int value;
cin >> value;
tail->next = new Node{value, nullptr};
tail = tail->next;
}
return head;
}
// 查找并返回是否存在目标值
bool search(Node* head, int target) {
Node* current = head;
while (current != nullptr) {
if (current->data == target) {
cout << "yes" << endl;
return true;
}
current = current->next;
}
cout << "no" << endl;
return false;
}
int main() {
int n;
cin >> n; // 输入元素个数
Node* listHead = createList(n); // 构建链表
int target;
cin >> target; // 输入要查找的值
search(listHead, target); // 检查并输出结果
delete listHead; // 清理内存
return 0;
}
```
在这个程序中,我们首先定义了一个链表节点`Node`,然后通过用户输入构建链表。`search`函数遍历整个链表,如果找到目标值则返回`true`并输出"Yes",找不到则输出"No"。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)