2

我正在尝试检查给定链表中是否存在实体。这是我的代码:

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

从我标记为“问题行”的行开始,if 语句的部分

(helpNode->data != NULL)

我收到错误 CXX0017(未找到符号“”)和错误 CXX0030(无法评估表达式)。

如果链表中没有实体,则此代码有效 - 换句话说,如果头为空。

Node 构造函数如下所示:

LinkedList::Node::Node()
{  
next=NULL;
data=NULL;
} 

我也试过了:

(helpNode != NULL)

和节点构造函数

LinkedList::Node::Node(){}

所有组合都返回相同的错误。有什么建议么?

4

2 回答 2

2

首先,我建议使用您的代码修复一些问题。

在您的循环中,您在测试之前data检查成员以查看是否实际有效。想象一下,你在最后一个节点上——并且在下面的执行结束时——现在在顶部检查了什么?helpNode helpNode

helpNode=helpNode->next;

其次,一旦你检查了helpNode,接下来你应该data在检查 的属性之前检查它是否有效data,如果dataNULL怎么办?

现在想想你的循环正在检查什么,它正在检查 ,getID() != ID但在循环内部你正在测试ID, getID() == ID? 那有意义吗?

我建议在您的循环中,您只需检查下一个节点是否data存在,然后在循环中检查是否ID匹配,如果为真则返回。

于 2011-05-20T07:26:49.447 回答
0

好线

while ((helpNode->data->indicatedEntity->getID() != ID) && (helpNode->data != NULL))

如果 data 为 NULL 可能是个问题,因为那时您将尝试访问 NULL->indicatedEntity

进一步,如果指示实体为 NULL,那么您正在尝试访问 NULL->getID()

您可以将其重写为

while (helpNode->data != NULL && helpNode->data->indicatedEntity != NULL && helpNode->data->indicatedEntity->getID() != ID)

这看起来不太好,但它确实确保您的指针在尝试访问它们之前不为空。

于 2011-05-20T07:28:02.677 回答