C++ 代码 设单链表的结点是按关键字的值从小到大排列的,试写出对此表的查找程序并调试
时间: 2023-12-10 13:42:34 浏览: 27
以下是基于单链表的查找程序的 C++ 实现:
```cpp
#include <iostream>
using namespace std;
// 定义单链表的结点
struct ListNode {
int val; // 结点的值
ListNode* next; // 指向下一个结点的指针
ListNode(int x) : val(x), next(NULL) {}
};
// 查找单链表中是否存在某个值为 key 的结点
bool searchList(ListNode* head, int key) {
ListNode* cur = head;
while (cur != NULL) {
if (cur->val == key)
return true;
else if (cur->val > key)
return false;
cur = cur->next;
}
return false;
}
int main() {
// 创建一个单链表
ListNode* head = new ListNode(1);
head->next = new ListNode(3);
head->next->next = new ListNode(5);
head->next->next->next = new ListNode(7);
head->next->next->next->next = new ListNode(9);
// 查找值为 5 的结点
if (searchList(head, 5))
cout << "The list contains node with value 5." << endl;
else
cout << "The list does not contain node with value 5." << endl;
// 查找值为 6 的结点
if (searchList(head, 6))
cout << "The list contains node with value 6." << endl;
else
cout << "The list does not contain node with value 6." << endl;
return 0;
}
```
上述代码中,我们首先定义了一个单链表的结点 `ListNode`,其中 `val` 表示结点的值,`next` 表示指向下一个结点的指针。然后,我们实现了一个查找函数 `searchList`,该函数接受两个参数:单链表的头结点 `head` 和要查找的值 `key`。在函数中,我们使用一个指针 `cur` 遍历整个链表,当遇到某个结点的值等于 `key` 时,返回 true;当遇到某个结点的值大于 `key` 时,直接返回 false,因为单链表是按照结点的值从小到大排列的。最后,如果整个链表都遍历完了还没有找到值为 `key` 的结点,则返回 false。
在主函数中,我们首先创建了一个单链表,然后分别查找值为 5 和 6 的结点,并输出结果。
需要注意的是,由于我们使用了动态内存分配来创建单链表,因此在程序结束时需要手动释放内存,否则会造成内存泄漏。