Can every recursion be changed to iteration?

后端 未结 5 683
遇见更好的自我
遇见更好的自我 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:55

    It is generally possible to convert any recursive algorithm into loop. The method is simple: we can imitate how the compiler generate code for function call: entering function, returning from function, and continue execution.

    To turn a recursive function into an iterative loop, you can:

    • Define a record, which stores the arguments to the function and the local variables. This is equivalent to stack frame.
    • Define a stack, to which records a pushed. This is analogy to the program stack.
    • When a function is called, create a record of the current value of the arguments and local variables and push to stack.
    • When you return from the function, pop out from stack and overwrite the current value with that from the record.

    The whole process above is done in a while loop, which will exit when the stack is empty,

提交回复
热议问题