C++ 链接列表简单的问题
C++ Linkedlist simple question
我正在尝试检查给定的链接列表中是否存在实体。 这是我的代码:
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(){}
所有组合都返回相同的错误。 有什么建议吗?
我建议用你的代码修复一些问题。
在循环中,您在测试之前检查helpNode
的data
成员,以查看helpNode
是否真正有效。想象一下,您在最后一个节点上 - 在执行以下命令结束时 - 现在在顶部检查什么?
helpNode=helpNode->next;
其次,一旦你检查了helpNode
,接下来你应该在检查data
的属性之前检查data
是否有效,如果data
NULL
怎么办?
现在想想你的循环正在检查什么,它正在检查那个getID() != ID
,然而在循环中你正在测试ID
,getID() == 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)
这看起来不太好,但它确实确保您的指针在尝试访问它们之前不为空。
- 关于简单C++函数(is_palindrome)的逻辑的问题
- 退出简单while循环时出现问题
- 关于 c++ 函数中指针赋值的简单问题
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- Opengl问题:很可能是简单的纹理问题
- 简单的问题 - 如何从单独的"结构"内的'class'访问变量?
- 运行简单的.oct文件时Octave崩溃,我的代码出了什么问题?
- 开发简单的时钟和日期类时遇到问题
- macos GCC 工具链编译简单 hello 世界的问题
- 具有 std:out_of_range 问题的简单密码 (C++)
- Qt的新信号/时隙语法问题 - 连接到一个简单的函数
- 这个简单的 C++ 递归函数来反转字符串有什么问题?
- 创建一个简单的计算器,添加时遇到问题
- 简单的最大除数问题 c++ 实现抛出时间限制已超出
- 这段简单的代码有什么问题?
- 通过此指针访问时的成员差异和自身的成员指针(简单的 QT 示例问题)
- 具有编译问题的简单(递归)可变参数模板"accumulate_for"函数
- C / C++链接问题与非常简单的设置
- 简单的游戏数据库问题
- 异常处理语法问题简单