赞
踩
递归 尾递归
Here you will learn about what is tail recursion with example.
在这里,您将通过示例了解什么是尾递归。
Tail recursion refers to recursive call at last line. The tail recursive functions considered better as the recursive call is at the last statement so there is nothing left to do in the current function. It saves the current function’s stack frame is of no use.
尾递归是指最后一行的递归调用。 尾部递归函数被认为更好,因为递归调用位于最后一条语句中,因此当前函数中无事可做。 保存当前函数的堆栈框架是没有用的。
Tail recursion can be eliminated by changing the recursive call to a goto preceded by a set of assignments per function call. This simulates the recursive call because nothing needs to be saved after the recursive call finishes. We can just goto the top of the function with the values that would have been used in a recursive call.
通过将递归调用更改为goto,并在每个函数调用之前分配一组分配,可以消除尾递归。 这模拟了递归调用,因为在递归调用完成之后不需要保存任何内容。 我们可以使用递归调用中使用的值转到函数顶部。
- void TOH(int n,char x,char y,char z)
- {
- if(n>0)
- {
- TOH(n-1,x,z,y);
- printf("\n%c-> %c",x,y);
- TOH(n-1,z,y,x); //tail recursion
- }
- }
- void TOH(int n,char x,char y,char z)
- {
- char temp;
- label:
- if(n>0)
- {
- TOH(n-1,x,z,y);
- printf("\n%c-> %c",x,y);
- temp=x;
- x=z;
- z=temp;
- n=n-1;
- goto label;
- }
- }
翻译自: https://www.thecrazyprogrammer.com/2014/07/what-is-tail-recursion.html
递归 尾递归
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。