C++ 递归函数C+的问题+;
我有一个很短的递归函数要编写,当我通过g++运行它时,我的函数返回seg fault 11时遇到了一个问题。我对递归很在行,而且刚刚开始学习。如果你有任何建议,请告诉我!目标是计算有多少节点的值大于输入值“m”。以下是我的代码:C++ 递归函数C+的问题+;,c++,recursion,linked-list,C++,Recursion,Linked List,我有一个很短的递归函数要编写,当我通过g++运行它时,我的函数返回seg fault 11时遇到了一个问题。我对递归很在行,而且刚刚开始学习。如果你有任何建议,请告诉我!目标是计算有多少节点的值大于输入值“m”。以下是我的代码: int LinkedList::countOccurrencesMoreThanRec(int m) { // first do the base cases that do not require recursion if (head == NULL)
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之类的库上,因为STL可以免费为您提供出色的数据结构(其他同事都能理解!) 然而,要以递归的方式完成您试图实现的目标,您可以将“answer”int设置为类成员、全局变量(抖动)或将答案传递给函数的每次调用(在第一个实例中传递零),但我不能强调递归方法不是解决此问题的正确方法。答案变量首先在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;
}
void LinkedList::countOccurrencesMoreThan(int值){
节点*节点=此->头部;
int=0;
while(节点!=NULL){
如果(节点->获取值()>v){
++事件;
}
node=node->getNext();
}
std::cout,是的,我知道这在没有递归的情况下要容易得多,但是我需要在countoccurrences
中使用递归,是否保证参数h
不为null?如果((h->getNext())==null,可能
条件在h
为空时会导致segfault。我相信我在第二个条件中进行了测试,以确保它不为空。当我修复该问题时,我的程序会说,无论链接列表中有多少个数字,它只会在我测试的每个数字中找到一个值。对此有什么想法吗?是的,这是我注意到的另一个问题。你必须这样做显著更改程序逻辑以解决此问题;请注意,更改answer
值的唯一时间是在查看列表中的最后一项时。