Can every recursion be changed to iteration?

后端 未结 5 717
遇见更好的自我
遇见更好的自我 2021-01-13 19:14

Is every recursive function convertible to iteration? What characteristic should a recursive function have in order for it to be implemented using iteration?

<
5条回答
  •  不要未来只要你来
    2021-01-13 19:52

    Yes, every recursive function can be converted to an iterative one by following a rather mechanical process.

    Recall that compilers implement recursion by using a stack, which is typically implemented in the CPU's hardware. You can build a software stack of your own, make it suitable for keeping the state of your function (i.e. its local variables), push the initial state onto that stack, and write a while loop that pushes new state onto the stack instead of making a recursive call, popping the stack instead of returning, and continuing the process while the stack is not empty.

提交回复
热议问题