Converting an iterative function to recursive

前端 未结 5 672
执笔经年
执笔经年 2020-12-21 15:28

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

5条回答
  •  天涯浪人
    2020-12-21 15:51

    How about this :

    int count(node *start){  
       if(!start) return 0;  
       int countValue = 0; 
       return count(start,start,&countValue);
    }
    
    
    int count(node *start, node *next, int *count){  
        if(start == next)//circular list so this is your base
           return *count;
        if(next->next->roll_no) == 20){  
             *count++;
        }  
        return count(start,next->next,count);  
    }
    

    It is not custom for recursive functions to modify input params though.
    Nor to use use global variable.
    This is the first approach I could come up

提交回复
热议问题