C++ 链接列表简单的问题

C++ Linkedlist simple question

本文关键字:问题 简单 列表 链接 C++      更新时间:2023-10-16

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

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(无法计算表达式)。

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

节点构造函数如下所示:

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

我也尝试过以下行:

(helpNode != NULL)

和节点构造函数

LinkedList::Node::Node(){}

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

首先,

我建议用你的代码修复一些问题。

在循环中,您在测试之前检查helpNodedata成员,以查看helpNode是否真正有效。想象一下,您在最后一个节点上 - 在执行以下命令结束时 - 现在在顶部检查什么?

helpNode=helpNode->next;

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

现在想想你的循环正在检查什么,它正在检查那个getID() != ID,然而在循环中你正在测试IDgetID() == ID? 这有意义吗?

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

好吧,这条线

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

如果数据为 NULL,则可能会出现问题,因为这样您将尝试访问 NULL->指示实体

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

您可以将其重写为

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

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