C ++有序链接列表搜索功能算法逻辑

时间:2013-10-16 16:58:33

标签: c++ algorithm search linked-list

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

5 个答案:

答案 0 :(得分:1)

如果找到密钥key == temp->key将为真且temp != NULL将为false,则:

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

OR:

if (temp != NULL)     // Make sure node is found
{   
    return temp; // If found, return appropriate value
}

答案 1 :(得分:1)

试试这段代码:

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

答案 2 :(得分:0)

您不需要if。只需返回temp。如果列表中存在正确的密钥,temp将指向它,否则它是NULL

答案 3 :(得分:0)

这对你有用

if(temp != NULL) // Make sure node is found
{
    return temp; // Make sure node is found
}

答案 4 :(得分:0)

你可以这样做:

if(temp != NULL)     // Make sure node is found
{   
    return temp; // If found, return appropriate value
}

但更简单的只是

return temp;

因为如果temp为null,则无论如何都要返回null。

相关问题