These days just and friends talk about recursion, suddenly found a lot of friends for the "tail recursion" concept is more vague, online search did not find a thorough explanation of the details of the information, so wrote an article, the right to be an Internet data supplement.
Recursion and tail recursion
On the recursive operation, I believe that we are no strangers. Simply put, a function calls itself directly or indirectly, for direct or indirect recursion. For example, we can use recursion to compute the length of a one-way list:
public class Node
{
public Node(int value, Node next)
{
this.Value = value;
this.Next = next;
}
public int Value { get; private set; }
public Node Next { get; private set; }
}
Write a recursive GetLength method:
public static int GetLengthRecursively(Node head)
{
if (head == null) return 0;
return GetLengthRecursively(head.Next) + 1;
}
When invoked, the Getlengthrecursively method calls itself continuously until the recursive exit is satisfied. Some understanding of the recursive friend must guess, if a single necklace table is very long, then the above method may encounter stack overflow, that is, throw stackoverflowexception. This is because each thread, when executing the code, will allocate a certain size of the stack space (Windows system is 1M), each method call in the stack to store certain information (such as parameters, local variables, return address, etc.), this information will take up a little space, thousands of such space accumulated, Naturally more than the stack space of the thread. But this problem is not without solution, we just have to change the recursion to the following form (in this article we do not consider the solution of the non-recursive):
public static int GetLengthTailRecursively(Node head, int acc)
{
if (head == null) return acc;
return GetLengthTailRecursively(head.Next, acc + 1);
}