Tail recursion and Continuation

Source: Internet
Author: User

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);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.