C++有序链表搜索函数算法逻辑
C++ Ordered Linked List Search Function Algorithm logic
我是C++新手,我正在尝试编写一个算法来搜索链表,但我的逻辑有点麻烦。这???粗体问号是我遇到问题的部分。我感谢对此的任何帮助。
ListNode *MyLinkedList::Search(int key)
{
ListNode *temp = head; // Assume ListNode is a structure and contains the variable int key;
// Search for the key
while((temp != NULL) && (key != temp->key))
{
temp = temp -> next; // Advance to next node
{
if(**???**) // Make sure node is found
{
return **???**; // If found, return appropriate value
}
else
{
return NULL; // return NULL when not found
}
}
如果找到密钥key == temp->key
将为真,temp != NULL
为假,则
if(key == temp->key) // Make sure node is found
{
return temp; // If found, return appropriate value
}
或:
if (temp != NULL) // Make sure node is found
{
return temp; // If found, return appropriate value
}
试试这段代码:
ListNode *MyLinkedList::Search(int key, ListNode *head)
{
ListNode *temp = head; // Assume ListNode is a structure and contains the variable int key;
// Search for the key
while(temp != NULL)
{
if (key == temp->key)
return temp;
temp = temp -> next; // Advance to next node
}
return NULL; // return NULL when not found
}
编辑
如果您不需要编写自己的容器,则应使用 stl 中的列表和 find 算法;它们经过测试且安全:
http://en.cppreference.com/w/cpp/container/list
http://en.cppreference.com/w/cpp/algorithm/find
你不需要if
.只需返回temp
.如果列表中存在正确的键,temp
将指向它,否则NULL
。
这将
为你工作
if(temp != NULL) // Make sure node is found
{
return temp; // Make sure node is found
}
你可以
这样做:
if(temp != NULL) // Make sure node is found
{
return temp; // If found, return appropriate value
}
但更简单的只是
return temp;
因为如果 temp 为空,您仍然希望返回 null。
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- STL算法函数在多个一维容器上的使用
- A*算法中魔方的启发式函数 人工智能
- 使用指针算法修改函数中的 2D 数组
- 如何将 c++ get 函数代码转换为 opencv 算法中使用的 python
- 如何在算法中使用谓词函数find_if?
- 我们如何并行运行算法的 n 个实例并以有效的方式计算结果函数的平均值?
- 如何在复杂的算法中处理goto函数?
- 快速排序函数在快速排序算法中如何工作?
- 在 c++ 或 python 中生成一个体面的视差图以在 Raspberry Pi 上实现的最佳方法(算法或函数)是什么
- 阴算法(音高检测) - 差分函数的替代
- 算法中的排序函数返回错误
- 如何处理算法中具有不同名称成员函数的类?
- STL算法函数,如累加,如果传递给它们的函数接受引用,请避免复制
- 欧几里得算法函数参数
- STL 算法函数模板
- 为什么我必须始终在 STL 的算法函数中显式指定范围,即使我想处理整个容器?
- 算法函数:将其作为模板或采用std::function参数
- 为std算法函数创建一个包装器,用容器代替迭代器
- STL 算法函数名称解析