Data structure (20) stack and recursion

Source: Internet
Author: User
Tags mathematical functions

    • Introduction
    • Recursive
      • N-Order Hanoi tower problem
        • Algorithm
        • Analytical
        • Hanoi 3-Step Process Demo

Introduction

The previous stage uses the stack to implement the expression evaluation, bracket matching and digital conversion. This time, we introduce another important level of application of the stack-recursion

Recursive

The important application of the stack is to implement recursion in the programming language . A function called directly to itself or indirectly through a series of invocation statements is called a recursive function.

Recursion is a powerful tool in program design.

Recursion is a powerful tool in program design. First, many of the mathematical functions are recursively defined, for example:
factorial function:
F aCT(N)={1      ifN=1N ? F aCT(N?1)     ifN>0
2 Order Fibonacci series

Second, some data structures, such as binary tree, generalized table, etc., due to the inherent recursive nature of the structure, their operations can be recursively described.

Third, there is a class of problems, although the problem itself has no obvious recursive structure, but recursive solution is more simple than iterative solution, such as eight queen problem, Hanoi Tower problem.

N-Order Hanoi tower problem

Suppose there are 3 tower seats named X, Y, z, and a disk with n diameters different in size and small to large numbered 1,2,......,n, as in Tower X.

It is now required to move the n discs on the x axis to Z and still stack in the same order, and the round block movement must follow the following rules:

(1) Only one disc can be moved at a time.

(2) The disc can be inserted into any tower seat in X, Y, Z.

(3) A large disc can not be pressed on a smaller disc at any time.

How to realize the operation of moving disk? When n=1 , the problem is simple, simply move the disc numbered 1 from the Tower X directly to the tower Z; n>1 , the tower y should be used as an auxiliary tower, if it can be managed to be pressed on a disk with the number n n? 1 From Tower X (in accordance with the above rules) to the tower Y, you can first n From the tower X to the Tower Z, and then on the Tower y n? 1 A disc (according to the above law) is moved to Tower Z. And how will n? 1 The problem of moving a disc from one tower to another is a problem with the same characteristic attribute as the original problem, but the size of the problem is only 1 smaller, so it can be solved by the same method.

Algorithm
intCount=0; voidMove(CharXintNCharz); void Hanoi (intNCharXCharYCharZ) {//Algorithm 3.5  //The n discs numbered 1 to n on the tower x in diameter from small to large and above are moved by rules  //Tower Z, y can be used as an auxiliary tower seat.   //Move action (x, N, z) can be defined as:  //(c is a global variable with an initial value of 0, and a moving count)  //printf ("%i. Move disk%i from%c to%c\n", ++c, N, x, z);  if(n==1)Move(X,1, z);//The disc numbered 1 is moved from X to Z  Else{Hanoi (n1, x,z,y);Move(x, n, z);//The disc numbered n is moved from X to ZHanoi (n1, y, x, z);//Move the disc numbered 1 to n-1 on Y to z,x as an auxiliary tower}}voidMove(CharXintNCharZ) {printf ("%2i. Move disk%i from%c to%c\n ", ++count,n,x,z);}
Analytical

The above algorithm is obviously a recursive function, in function execution function, need to make a self-call. So, how is this recursive function called? Let's look at the case where any two functions are called directly.

In a high-level language program, the link message and the message interaction between the calling function and the called function need to be done through the stack.

Typically, when another function is called during the run of a function, the system needs to complete 3 things before running the called function:
(1) Pass all the actual parameters, return address and other information to the called function to save.
(2) Assign a store to the local variables of the modulated function.
(3) Transfer control to the entry of the called function.

The system should also complete 3 pieces of work before the called function returns to the calling function:
(1) Save the computed result of the called function
(2) Releasing the data area of the called function
(3) Transfer control to the calling function according to the return address saved by the called function. When there are multiple calls that make up a nested call, the information transfer and control transfer between the above functions must be implemented by the "stack" in accordance with the principle of "back call first", that is, the system arranges the data space required for the entire program to run in a stack, allocating a store to the top of the stack whenever a function is called, Whenever you exit from a function and then release its storage, the data area of the function that is currently running must be at the top of the stack.

A recursive function runs like a nested call to multiple functions, except that both the calling function and the called function are the same function. Therefore, one important concept associated with each invocation is the "hierarchy" in which the recursive function runs. Assuming that the main function calling the recursive function is a No. 0 layer, the recursive function is called from the main function into the 1th layer, and the function is called recursively from layer I to enter the "next layer", that is, the first i+1 layer. Conversely, the exit layer I recursion should return to the "previous layer", that is, the i-1 layer. To ensure proper execution of recursive functions, a "recursive work stack" is set up as the data store used during the entire recursive function operation.

The required information for each level of recursion constitutes a "working record", which includes all the actual parameters, all local variables, and the return address of the previous layer. Each entry into a layer of recursion results in a new work record pressed into the top of the stack. Each exit level recursion, from the top of the stack to eject a work record, the current execution layer of the work record must be a recursive work stack top of the work record, called the record as "activity record", and said that indicates the activity record of the stack top pointer is "current environment pointer."

Hanoi 3-Step Process Demo

In practice, the value of a parameter is not necessarily passed between the calling function and the called function, and the address of the parameter can be passed.

void Hanoi (intNCharXCharYCharZ) {//Algorithm 3.5  //The n discs numbered 1 to n on the tower x in diameter from small to large and above are moved by rules  //Tower Z, y can be used as an auxiliary tower seat.   //Move action (x, N, z) can be defined as:  //(c is a global variable with an initial value of 0, and a moving count)  //printf ("%i. Move disk%i from%c to%c\n", ++c, N, x, z);1{2   if(n==1)3       Move(X,1, z);//The disc numbered 1 is moved from X to Z4     Else{5Hanoi (n1, x,z,y);6      Move(x, n, z);//The disc numbered n is moved from X to Z7Hanoi (n1, y, x, z);//Move the disc numbered 1 to n-1 on Y to z,x as an auxiliary tower8}9}

The above algorithm is a recursive diagram of the algorithm description, the statement line, then the above description is shown:

The next step is to implement the Hanoi Tower and eight queens.

Data structure (20) 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.