Converting an iterative function to recursive

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

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

    The base case is "the list is empty" or "we are at the end of the list". Then you recurse by taking the rest of the list (without the item we just looked at) and doing the exact same thing.

    Note that this is not tail recursive (although it may get optimised into a tail recursive option), so it will grow the stack and may explode.

    Tail recursively:

    int count_recursive (node* current, node* start, int c) {
      if (current == NULL)
        return c;
      if (current->next == start)
        return (current->roll_no == 20 ? 1 : 0) + c;
      if (current->roll_no == 20)
        return count_recursive(current->next, start, c+1);
      else
        return count_recursive(current->next, start, c);
    }
    int count(node* start) {
      return count_recursive(start, start, 0);
    }
    

    The tail recursive option is more likely to be optimised into a loop by the compiler, but a sufficiently intelligent compiler should turn them both into a loop.

提交回复
热议问题