newbieLinuxCpp
newbieLinuxCpp

Reputation: 486

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. 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;
}

Upvotes: 0

Views: 5766

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258628

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.

Upvotes: 1

Related Questions