0
votes

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();
    }


}
2
How is getLink() defined? contains looks ok (except that it's missing return false.RedX
contains("element") is vastly different from contains(element).molbdnilo

2 Answers

2
votes

You are using a literal rather then a variable in your method call:

if (contains("element") == true)

Should be:

if (contains(element) == true)
1
votes

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.