[英]C++ Linked List: IndexOf of an object
I am trying to find an index of a given object in my linked list. 我试图在链接列表中找到给定对象的索引。 I want to return -1 is the object doesn't exist in my list.
我想返回-1,因为该对象在列表中不存在。 Below is my code, please guide me.
以下是我的代码,请指导我。
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;
}
Why not return from inside the loop? 为什么不从循环内部返回?
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;
}
You could also store an auxiliary that tells you whether the node was found or not, but this approach is cleaner IMO. 您还可以存储一个辅助程序,以告诉您是否找到了该节点,但是这种方法更干净。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.