因此,我的教授希望我们为此类“ addressBookType”类的链表设计递归函数,该类源自其他4个类。该程序基本上会创建一个包含该人的姓名,地址,日期和关系的地址簿,每个地址簿都有自己的类。
她要执行的递归功能是打印,追加,删除和顺序搜索。
除了顺序搜索功能外,我都对它们进行了递归。
以下是原始版本和递归版本:
bool addressBookType::seqSearch(extPersonType item) const
{
bool found = false;
ListNode *nodePtr; // pointer to traverse the list
nodePtr = head; // start the search at the first node
found = seqSearchRecursive(nodePtr, item); // call recursive function
if(found)
found = (nodePtr->value == item); // test for equality
return found;
}
bool addressBookType::seqSearchRecursive(ListNode *nPtr, extPersonType obj) const
{
if(nPtr == NULL) // return false if value not found
{
return false;
}
else if(nPtr->value == obj) // return true if object found
{
return true;
}
else
seqSearchRecursive(nPtr->next, obj); // call recursive funct with next value
}
我的问题是出现输出错误。当我从列表中删除对象并进行搜索时,它返回了false
。然后,我在列表中搜索了一个对象,它返回了false
。因此,使该函数总是返回false的任何事情。有人有什么建议吗?
答案 0 :(得分:0)
似乎您在return
块中忘记了一个else
关键字。因此,seqSearchRecursive
被调用,但是其结果未使用,并且函数到达结尾而没有返回任何内容,对于非void函数,这被认为是undefined behavior。您可以使用-Wall
和-Wextra
编译器标志来获取有关此类问题的通知。
如果obj
不是基本类型的别名,我也建议将const extPersonType& obj
传递为extPersonType
。而且由于c ++ 11,nullptr
比NULL
更为可取。