Converting an iterative function to recursive

前端 未结 5 698
执笔经年
执笔经年 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:48

    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));
    }
    

提交回复
热议问题