C++ Linkedlist simple question
I'm trying to check if an entity exists in a given linkedlist. This is my code:
bool LinkedList::existByID(int ID)
{
//create node to search through the list
Node * helpNode;
//start it at the top of the list
helpNode = head;
if (head == NULL)
{
return false;
}
//while the item has not yet been found
while ((helpNode->data->indicatedEntity->getID() != ID) && (helpNod开发者_如何学编程e->data != NULL))
{
if (helpNode->data->indicatedEntity->getID() == ID)
{
//return true - the data exists
return true;
}
else
//if the data has not been found, move on
helpNode=helpNode->next;
}
//if the data has not been found and the end of the
//list has been reached, return false - the item does
//not exist
return false;
}
From the line I marked as the "problem line", the part of the if statement
(helpNode->data != NULL)
I get error CXX0017 (symbol "" not found) and error CXX0030 (expression cannot be evaluated).
This code works if there are no entities in the linkedlist - in other words, if the head is null.
The Node constructor looks like this:
LinkedList::Node::Node()
{
next=NULL;
data=NULL;
}
I've also tried it with the line:
(helpNode != NULL)
and Node constructor
LinkedList::Node::Node(){}
All combinations return the same errors. Any suggestions?
Firstly I recommend fixing a few things with your code.
In your loop you check the data
member of helpNode
before testing to see if helpNode
is actually valid. Imagine you are on the last node - and at the end of the while the following executes - now what gets checked at the top?
helpNode=helpNode->next;
Secondly, once you've checked for helpNode
, next you should check that data
is valid before checking attributes of data
, what if data
is NULL
?
And now think about what your loop is checking, it's checking that getID() != ID
, and yet inside the loop you are testing for the ID
, getID() == ID
? does that make sense?
I recommend that in your loop, you just check that the next node and data
exists, and then within the loop check that the ID
matches, and return if true.
Well the line
while ((helpNode->data->indicatedEntity->getID() != ID) && (helpNode->data != NULL))
might be a problem if data is NULL, because then you would be trying to access NULL->indicatedEntity
further if indicatedEntity is NULL, then you are trying to access NULL->getID()
you can rewrite it to
while (helpNode->data != NULL && helpNode->data->indicatedEntity != NULL && helpNode->data->indicatedEntity->getID() != ID)
which doesnt look nice, but it does ensure your pointers are not null before trying to access them.
精彩评论