Converting an iterative function to recursive

前端 未结 5 675
执笔经年
执笔经年 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 16:01

    int count(struct node * ptr)
    {
        return ptr==NULL ? 0 : (ptr->roll_no == 20 ? 1:0) + count(ptr->next);
    }
    

    UPDATE: it appears the list is circular.

    int count(struct node * start, struct node * ptr)
    {
        return ptr==NULL || ptr->next == start ? 0 
                                               : (ptr->roll_no == 20 ? 1:0) 
                                                 + count(start, ptr->next);
    }
    /* to be called like: */
    cnt = count (the_list, the_list);
    

    UPDATE 2: (failure to count the last node)

    int count(struct node * start, struct node * ptr)
    {
        return ptr==NULL  ? 0 
                          : (ptr->roll_no == 20 ? 1:0) 
                            + ptr->next == start ? 0
                                                 : count(start, ptr->next);
    }
    

    UPDATE3: it did need an extra pair of parentheses...

    #include 
    
    struct node {
            struct node *next;
            int roll_no;
            };
    
    struct node nodes[8] =
    {{ nodes+1, 20} ,{ nodes+2, 0}
    ,{ nodes+3, 20} ,{ nodes+4, 0}
    ,{ nodes+5, 20} ,{ nodes+6, 0}
    ,{ nodes+7, 20} ,{ nodes+0, 0}
    };
    
    unsigned count(struct node * start, struct node * ptr)
    {
        return ptr==NULL
                  ? 0
                  : (ptr->roll_no == 20 ? 1:0)
                    + (ptr->next == start
                        ? 0
                        : count(start, ptr->next)
                      )
                  ;
    }
    
    #define COUNT(p) count(p,p)
    
    int main (void)
    {
    unsigned cnt,idx;
    
    for (idx = 0; idx < 8 ; idx++) {
        cnt = COUNT (nodes+idx);
        printf ("count@%u = %u\n", idx, cnt);
        }
    
    return 0;
    }
    

提交回复
热议问题