C ++ Linked List简单的问题

时间:2011-05-20 07:17:35

标签: c++ pointers linked-list singly-linked-list null-pointer

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

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。

Node构造函数如下所示:

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

我也试过这行:

(helpNode != NULL)

和Node构造函数

LinkedList::Node::Node(){}

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

2 个答案:

答案 0 :(得分:2)

首先,我建议您使用代码修复一些内容。

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

helpNode=helpNode->next;

其次,一旦您检查了helpNode,接下来应检查data是否有效,然后再检查data的属性,如果data是{{1 }}?

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

我建议你在循环中检查下一个节点getID() == ID是否存在,然后在循环内检查data是否匹配,如果为真则返回。

答案 1 :(得分:0)

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

如果数据为NULL,则

可能是一个问题,因为那时您将尝试访问NULL-> shownEntity

如果shownEntity为NULL,那么你试图访问NULL-> getID()

您可以将其重写为

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

看起来并不好看,但确实在尝试访问指针之前确保指针不为空。