转换一个迭代函数来递归 [英] Converting an iterative function to recursive
本文介绍了转换一个迭代函数来递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道人们通常会问这个问题倒过来,但我有以下问题:
我有这个迭代函数计算包含数据值20。现在,一个循环双向链表的所有节点,如何使这个递归的,会是怎样的基本情况(终止的情况下)的递归函数?
任何帮助是AP preciated:
诠释计数(节点*开始)
{
INT℃;
C = 0;
如果(开始== NULL)
返回0;
如果((开始 - > roll_no)== 20)
C = 1;
节点*电流=启动;
而(电流 - >!=旁边开始)
{
如果((电流 - >下一步 - > roll_no)== 20){
C ++;
}
电流=电流 - >接着,
} 返回℃;
}
解决方案
我觉得这应该工作(但要注意,它需要一个额外的参数跟踪开始):
诠释计数(节点*开始)
{
返回count_helper(启动,启动);
}
INT count_helper(节点*电流,节点*启动)
{
INT℃;
C = 0;
如果(当前== NULL)
返回0;
如果((电流 - > roll_no)== 20)
C = 1;
如果(电流 - >接下来==开始)返回℃;
返回(C + count_helper(电流 - >接着,启动));
}
I know people usually ask this question the other way round, but I have the following problem: I have this iterative function which counts all the nodes in a circular doubly link list containing the data value 20. Now, how do I make this recursive, what will be the base case (terminating case) for the recursive function? Any help is appreciated:
int count(node *start)
{
int c;
c = 0;
if(start == NULL)
return 0;
if((start->roll_no) == 20)
c = 1;
node *current = start;
while(current->next != start)
{
if((current->next->roll_no) == 20){
c++;
}
current = current->next;
}
return c;
}
解决方案
I think this should work (but note that it requires an extra argument for tracking start):
int count(node *start)
{
return count_helper(start, start);
}
int count_helper(node *current, node *start)
{
int c;
c = 0;
if(current == NULL)
return 0;
if((current->roll_no) == 20)
c = 1;
if(current->next == start) return c;
return (c + count_helper(current->next, start));
}
这篇关于转换一个迭代函数来递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文