0

我试图在我的链表中找到给定对象的索引。我想返回 -1 是我的列表中不存在该对象。以下是我的代码,请指导我。

int List::indexOf(const Object& o) const
{
    Node* tempNode = first;
    int count = 0;
    while(tempNode != NULL)
    {
        if (o.compare(tempNode->o) == 0)
        {
            break;
        }
    ++count;
    tempNode = tempNode->next;
    }
    return count;
}
4

1 回答 1

1

为什么不从循环内部返回?

Node* tempNode = first;
    int count = 0;
    while(tempNode != NULL)
    {
       if (o.compare(tempNode->o) == 0)
       {
           //return the count when you found a match
           return count;
       }
       ++count;
       tempNode = tempNode->next;
    }
    //return -1 if no match is found
    return -1;
}

您还可以存储一个辅助信息,告诉您是否找到了节点,但这种方法更清洁 IMO。

于 2012-05-24T17:23:44.267 回答