The relationship between Java stack and recursion

Source: Internet
Author: User

Recently looked at Mark.Allen.Weiss's algorithm and data structure, saw inside the table, stack and queue, combined with the most recent works of the more recursive operation. So let's talk about recursion here.

Because at the beginning of the year to see the "Big Talk Data Results" ( recommended to see ), here is the concept: the function of the recursive call and the normal function call is the same, when the program executes to a function, the function into the stack operation, before the stack to do the main three things

1. Return the entry, return address, etc. returned to the called function to save

2. Allocating stack space

3. Ready to be called

The same is true for the stack:

1. Save the results of the operation

2. Eliminate Stack space

3. Put the results of the operation into the stack space exit

So it's not surprising that the compiler uses the stack to implement recursion by recursively storing some data and recovering the data in reverse order, in order to provide the requirements for later use, which is clearly consistent with the data structure of the stack.

Example

  

This procedure is known as an example of improper use of tail recursion. The tail recursive design is called recursively on the last line. The tail recursion can be manually removed by putting the code into a while loop and substituting a single assignment of each method parameter instead of a recursive call. The following is the syntax for removing recursion

In fact, in the process of code operations, the recursive which comes can always be completely removed (the compiler is converted into assembly language to complete the recursive removal); but it's rather tedious. The general method requires a stack, and this method is only worth using if you can put the lowest minimum value on the stack.

The relationship between Java stack and recursion

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.