Converting an iterative function to recursive

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

    There is no making this recursive, because there is no recursion in the structure, it is already a list.

    Usually, because recursion has a lot of overhead, you can rewrite such a function to iterative, by creating a list (or stack) of 'levels to do'. Instead of recursively calling the function, you can push the item on the stack, and loop your routine until the stack is empty.

    An example is listing a file tree. Instead of calling the function recursively for each found directory, you can also push the directory name on a stack of directories to process. That way, you don't have a large number of directory handles or iterators or whatever you're using, when you have a deeply nested tree.

    But none of that applies here, since you don't have a tree at all.

    It can be done, though: You could replace the while with a recursive call, but you would have to pass the original start, or make it global, or else you wouldn't know when to break the recursion. Also, though possible, you will get it trouble soon if you got a long list.

提交回复
热议问题