Function call Typically, when another function is called while a function is running, the system needs to complete 3 things before running the tuned function: (1) Passing all arguments, the return address (which is the address of the next statement when the call to the function is called), to the tuned function. (2) Allocating storage space for local variables of the function being tuned. (3) Transfer control to the inlet of the modulated function.
The system completes 3 things before returning the calling function from the called Function: (1) Saves the computed result of the tuned function. (2) Release the data area of the modulated function. (3) The control is transferred to the calling function according to the return address saved by the transferred function.
Recursion: A function calls itself directly or indirectly.
Thought is: To reduce the scale of the problem, to simplify and simplify, to seek n! Convert to (n-1)!, then converted to (n-2)! ....... Finally converted into (1)!. Like the Hanoi tower problem, this looks more complicated if you start with 10 weights and move from A to C. Just move the first 9 to B, then move 10th to C. The 9 How to move it, also in this way ... This is the recursive implementation Hanoi detailed code see the bottom loop and recursive comparison:
Recursion:
Easy to understand
Slow speed
Large storage space
Loops
not easy to understand
Fast Speed
Small Storage space
Recursive applications:
1. finding factorial
2.1+2+3+4+... +100 of and
3. Hanoi
4. Walk the Maze (CS implementation )
Application of recursion:
trees and forests are defined in a recursive way.
Many algorithms for trees and graphs are implemented recursively.
Many mathematical formulas are defined in a recursive way.
Fibonacci Sequence
3 5 8...
C Language Implementation Hanoi:
#include <stdio.h>void hanota (int num,char A,char B,char C) {//If there is only one element, move this element directly to C if (1==num) { printf (" Move%d elements from%c to%c\n ", num,a,c); }else{//If it is not the first element, first n-1 elements, with C move to B Hanota (num-1,a,c,b);//Then move the bottom element of A to C printf ("Move%d elements from%c to%c\n", NUM,A,C); Then the elements on B are moved to C Hanota (NUM-1,B,A,C) with the aid of a ;}} int main () { char a= ' A '; Char b= ' B '; Char c= ' C '; Hanota (3,a,b,c); return 0;}
In real life, if we solve the problem is more cumbersome, may wish to reduce the size of the problem to consider.
Data Structure Foundation (6)--Recursive and function call--Hanoi tower problem C language implementation