C++有序链表搜索函数算法逻辑

C++ Ordered Linked List Search Function Algorithm logic

本文关键字:算法 函数 搜索 链表 C++      更新时间:2023-10-16

我是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。