【发布时间】:2020-08-18 13:25:24
【问题描述】:
我试图将这个已经在我的程序中工作的方法转换为递归方式。因为我被要求这样做。问题是我已经尝试过见下文,但是在我的方法中,当尝试将方法值添加到他的位置时,这个值是一个很大的数字并创建分段。
这是我的迭代方法:
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
}
}
【问题讨论】:
-
显然你有两个结构,一个用于列表,一个用于节点。递归函数必须在节点上递归,而不是列表:您有三种情况:(1)节点为空:返回“未找到”; (2) 节点有你要查找的数据:返回位置; (3) 递归到
node->next。我认为您的实现递归地调用列表中的函数并且总是从头开始。