C++;有序链表搜索函数算法逻辑 我是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 } }

C++;有序链表搜索函数算法逻辑 我是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 } },c++,algorithm,search,linked-list,C++,Algorithm,Search,Linked List,如果找到该键,则key==temp->key将为真且temp!=NULL将为false,因此: if(key == temp->key) // Make sure node is found { return temp; // If found, return appropriate value } 或: 如果,则不需要。只需返回temp。如果列表中存在正确的键,temp将指向它,否则它将为NULL这对您适用 if(temp != NULL) // Make sur

如果找到该键,则
key==temp->key
将为真且
temp!=NULL
将为false,因此:

if(key == temp->key)     // Make sure node is found
{   
    return temp; // If found, return appropriate value
}
或:


如果,则不需要
。只需返回
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,您仍然希望返回null。

请尝试以下代码:

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算法;它们经过测试且安全:


除非这是家庭作业(或类似内容),否则您可能应该使用
std::list
std::find
。感谢大家的帮助,我的困惑现在已经消除了!
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
}