迭代方法到递归方法C语言



我已经尝试将这个已经在我的程序中工作的方法转换为递归方式。因为我被要求这么做。问题是我试着看到下面,但在我的方法中,当试图添加到方法值的位置时,这个值是一个很大的数字,并创建分段。

这是我的迭代方法:

int researchList_getPosByCountry(tResearchList* list, tCountry *country) {
// Check preconditions
assert(list != NULL);
tResearchListNode *prev = NULL;
int pos;

// check if is an empty list 
if (researchList_empty(list)) {
pos = -1;
}
else{
pos = 1;
prev = list->first;
while ((prev != NULL) && !country_equal(prev->e->country, country) ) {
prev = prev->next;
pos++;
}
}
if (prev == NULL) {
pos = -1;        
}
return pos;
}

这是我的递归方法:

assert(list != NULL);
tResearchListNode *prev;
int pos;

// check if is an empty list 
if (researchList_empty(list)) {
pos = -1;
}
else{
pos = 1;
prev = list->first;
if ((prev != NULL) && !country_equal(prev->e->country, country) ) {
prev = prev->next;
pos = pos + researchList_getPosByCountry(list, country); //Debugging the segmentation is here
}

}

您将得到一个无休止的递归,因为您总是从列表的开头开始调用researchList_getPosByCountry;一次又一次。。。

我建议您引入第二个(然后递归使用(函数,该函数用相应的下一个节点调用自己,并返回(a(如果没有找到节点,则可能的"最大"负数(从而将调用堆栈上的任何中间结果变成负数(,或返回0表示"找到了国家,到目前为止进行计数",或返回"1+下一次尝试"继续计数。递归部分可以如下所示;然后你需要从int researchList_getPosByCountry(tResearchList* list, tCountry *country)调用这个,并相应地解释一个否定的结果:

int researchList_getPosByCountry(tResearchListNode* node, tCountry *country) {
if (!node) {
return INT_MIN;
} else if (countryEqual(...)) {
return 0;
} else {
return 1 + researchList_getPosByCountry(node->next,country);
}
}

最新更新