I am attempting to search a list to check whether an item is already present before inserting. I am having trouble with the pointers; I understand that I need to set the pointer to the start of list but I keep getting compilation errors. Can anyone help? Here is my code:

bool List::IsThere(ItemType Item) const
// Post: If item is in the list IsThere is 
//       True: False otherwise
{        
       NodePtr loopPtr;
        
        if (Item == listPtr->item)
        {   return true;
            listPtr = listPtr->next;
        }
        else
        {// Search for node in rest of list
            loopPtr = listPtr;
            while (loopPtr->next->item != Item)
                  loopPtr = loopPtr->next;
            return true;
        }
 }

error: 32 C\ListType.cpp assignment of data-member `List::listPtr' in read-only structure

Recommended Answers

All 3 Replies

By the way,

if (Item == listPtr->item)
{   
         return true;
         listPtr = listPtr->next;
}

This is incorrect - You'll never set listPtr's next member since you're returning on the line before it. As soon as a function sees the "return" keyword, it exits that function immediately with the return type (if any).

Thanks, silly error; but that does not solve the problem. Here is how I understand the method: put pointer at beginning,search list if found return true else return false. That's right is it not?

bool List::IsThere(ItemType Item) const
// Post: If item is in the list IsThere is 
//       True: False otherwise
{
        NodePtr loopPtr;
        
        loopPtr = listPtr;
        if (Item == listPtr->item)
           return true;
        else
        // Search for node in rest of list
        {              
            while (loopPtr->next->item != Item)
                  loopPtr = loopPtr->next;
            return true;
        }
 
        return false;
}

still crashes

//set loop pointer to start of loop 
loopPtr = listPtr;

//look at all nodes in list
while (loopPtr != NULL)
{
   //if you find it
   if(loopPtr-> item == Item)
        //you can stop
        return true;
   else
        //otherwise look at next node in list
        loopPtr = loopPtr->next;
}
//if you get here, Item wasn't found in list
//so return false.
return false;

Some people prefer something like this, because it has only a single return statement in the sequence:

//declare and set a flag to a default value
bool found = false;

while (loopPtr != NULL)
{
   if(loopPtr-> item == Item)
   {
        found = true;
         //you can stop
         break;
   }
   else
        loopPtr = loopPtr->next;
}
return found;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.