c++递归函数的问题
Issue with recursive function C++
我有一个简短的递归函数要写,当我通过g++运行它时,我的函数有一个返回segfault 11的问题。我不擅长递归,才刚刚开始学习。如果你有任何建议,请告诉我!目标是计算有多少节点的值大于输入值"m"。
int LinkedList::countOccurrencesMoreThanRec(int m)
{
// first do the base cases that do not require recursion
if (head == NULL)
return -1;
int answer = 0;
if ((head -> getNext()) == NULL)
{
if ((head -> getValue()) > m)
answer ++;
return answer;
}
// if none of those were true, call the recursive helper method
Node *BatMan = head;
answer = countOccurrencesMoreThan(BatMan, m);
return answer;
}
/* countOccurrencesMoreThan
*
* private recursive method.
* TODO: fill in this method
*/
int LinkedList::countOccurrencesMoreThan(Node *h, int m)
{
// check for the base case(s)
int answer = 0;
if ((h -> getNext()) == NULL)
{
if ((h -> getValue()) > m)
answer++;
return answer;
}
// smaller case
Node *Bane = h;
answer = countOccurrencesMoreThan(Bane, m);
return answer;
// general case
}
你的评论在撒谎。
// smaller case
Node *Bane = h;
在这里,您将Bane
设置为传递给函数的相同值。你实际上不是测试列表中的下一个项目,你是在做同样的列表。
这不是代码中唯一的问题,但它至少可以帮助解决您提出的问题。
关于递归的第一个问题应该总是:我需要递归吗?当迭代LinkedList的元素时,绝对不需要递归。
其次,我强烈建议不要使用自己的链表类,因为编写自己的链表类所花费的时间最好花在学习诸如STL之类的库上,这些库可以免费提供出色的数据结构(其他同事也能理解!)。
然而,要完成您试图递归实现的目标,您可以将"答案"放入类成员,全局变量(颤音)或将答案传递给函数的每次调用(在第一个实例中传递零),但我不能强调递归方法不是解决此问题的正确方法。首先,answer变量在LinkedList类中没有位置,全局变量几乎总是邪恶的,传递一个你只是增加的值是低效和令人困惑的。
int LinkedList::countOccurrencesMoreThan(Node *h, int m, int answer)
{
if( h->getValue() > m ) {
++answer;
}
if (h -> getNext() == NULL)
{
return answer;
}
countOccurrencesMoreThan( h->getNext(), m, answer);
}
下面是一个使用简单LinkedList类的更好的非递归实现:
void LinkedList::countOccurrencesMoreThan(int value) {
Node* node = this->head;
int occurrences = 0;
while(node != NULL) {
if( node->getValue() > v ) {
++occurrences;
}
node = node->getNext();
}
std::cout << "occurrences = " << occurrences << std::endl;
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何在Elixir中调用递归函数并行
- 到连接组件算法的问题(递归)
- 递归函数有效,但无法记忆
- 为什么我的递归函数按降序打印,然后按升序打印?
- 为什么递归函数的最终输出是 5?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 返回不停止函数,递归函数问题?(编程练习,动态规划,Levenshtein 回溯)
- 跟踪递归函数时出现问题
- 这个简单的 C++ 递归函数来反转字符串有什么问题?
- 问题 - 递归函数以返回文本文件排列
- 递归函数中的许多参数会导致性能问题吗
- 实现用于查找路径的递归函数时出现问题
- 将数组传递给递归函数 c++ 时遇到问题
- 在运行递归函数时将新元素插入向量时出现问题
- Fencepost问题:我需要一个递归函数,当它第一次被调用时,它会跳过执行一个部分
- 带有for循环的递归函数:返回值问题
- 分划问题的递归函数
- c++递归函数的问题
- 选举投票递归函数-斯坦福CS106B问题