Reputation: 273
I am working on a linked list project and I have two functions that I can't get to work right.
First I have a insert function that adds an element to the list. But the function first wants to check if the element is already in the list. It should do that by using the bool function contain(). That should return true if the element is already in the list
my insert function:
void StringSet::insert(string element)
{
NodePtr temp =head;
if (contains("element") == true)
{
return;
}
if(head == NULL)
{
head = new StringNode;
head->setData(element);
head->setLink(NULL);
}
else
{
temp = new StringNode;
temp->setData(element);
temp->setLink(head);
head = temp;
}
}
And my contain function:
bool StringSet::contains(string element)
{
NodePtr temp = head;
while(temp != NULL)
{
if (temp->getData() == element)
{
cout<<"This country has already been registered!"<<endl;
return true;
}
temp = temp->getLink();
}
}
Upvotes: 0
Views: 176
Reputation: 310950
Function contains has undefined behaviour because it returns nothing in case when there is no target element in the list. Change it the following way
bool StringSet::contains( const string &element ) const
{
NodePtr temp = head;
while( temp != NULL && temp->getData() != element ) temp = temp->getLink();
return ( temp != NULL );
}
And change its call from
if (contains("element") == true)
to
if ( contains( element) )
because "element" is not the same as element.
Upvotes: 1
Reputation: 3276
You are using a literal rather then a variable in your method call:
if (contains("element") == true)
Should be:
if (contains(element) == true)
Upvotes: 2