08. Application of stack (II) and 08 Application
1. Stack application-recursion 1. Recursive Function: Call a function directly or indirectly by calling itself or through a series of call statements, called a recursive function. 2. Stack and recursive functions are actually a process of moving forward and returning, which is equivalent to the inbound and outbound stacks. In the forward phase, for each layer of recursion, the local variables, parameter values, and return addresses of the function are pushed into the stack. In the return phase, the local variables, parameter values, and return addresses at the top of the stack Are popped up (out of the stack) to return the rest of the code executed at the call level, that is, the call status is restored. 3. Recursive application-the Fibonacci series describes the breeding problem of rabbits. This series has an obvious characteristic: the sum of the two adjacent items in the front forms the next one. The mathematical model is: | 0. When n = 0, where n is the number of months F (n) = | 1, when n = 1 | F (n-1) + F (n-2) WHEN n> 1. Where n is the number of months that have passed, and F (n) is the number of rabbits in the nth month. Source code for Recursive Implementation:
/* The Fibonacci recursive function * prints the first 40 Fibonacci series */int Fb (int I) // I is the nth month {if (I <2) return I = 0? ; // When n = 0, n = 1, the total number of rabbits returned by the month = 0/1 return Fb (I-1) + Fb (n-2 ); // when n> 1, total number of rabbits returned by month I} int main () {int I; for (int I = 0; I <40; I ++) // calculate and print the number of rabbits in the first 40 months in sequence {printf ("% d", Fb (I);} return 0 ;}
Ii. Stack application-arithmetic expression evaluate value 1. infix expression to suffix expression (1) Target: infix expression "9 + (3-1) * 3 + 10/2 "converted to a suffix expression" 9 3 1-3 * + 10 2/+ "(2) Rule: traverse each number and symbol of the fix expression from left to right. If it is a number, it is output. If it is a symbol, it determines its priority with the top symbol of the stack. If it is a right brace or the priority is lower than the top symbol of the stack, the top elements of the stack are output in sequence, add the current symbol to the stack until the suffix expression is output. 2. suffix expression Calculation Result (1) Objective: To calculate the suffix expression "9 3 1-3 * + 10 2/+" (2) Rule: traverse each number and symbol of the expression from left to right. When it comes to a number, it goes into the stack. When it comes to a symbol, it goes out of the stack with two digits at the top of the stack for calculation, add the calculation result to the stack and get the final result. Conclusion: The Key to converting an infix expression into a suffix expression is the stack symbol used for operation. The key to the result of the operation of a suffix expression is the number used by the stack for operation.