3 32 + 5 3 *-
12 34 2-* 8/
At first glance, the two statements above are very strange, right? They are the inverse polish expression, which is the record of an expression mentioned here.
Now, prepare a very narrow cylinder with a bottom, like a slim Cup, which is exactly the same as a coin. Then, write "3", "32", "+" 5 "," 3 "," * ", and"-"on the paper. Remember, each piece of paper can either write only one number or only one operator number, and sort them in the above Order. Well, now let me know carefully, pick up the small disc one by one in sequence, and execute the following rules repeatedly:
1. If you are holding a number, simply put it into the cylinder;
2. If you are holding an operator number, do not put it in. First, extract two numbers from the cylinder (of course, the first is the top, the cylinder is very fine), and then place these two numbers for the operation specified by the operator number, write the result on a new piece of paper and put it in the tube. For example, if you are holding "+", You need to extract "32" and "3" in sequence and add them to "35 ", write "35" on a new piece of paper (now "34" and "12" can be thrown away) and put the new piece of paper into the cylinder.
When there is only one number in the cylinder, you can stop. I guess this number is 20. Yes, this is the value of this expression!
What we just operated on is actually a "stack". The stack is a data structure with a nature-LIFO-last input first output. You already have a deep understanding, just like a pile of dishes, you can only take them from the top, and put them on the top. The action to put in is called "inbound stack", and the action to take out is called "pop-up ". In the future, you can think of a stack as a pile of plates, or the small cylinder and small pieces of paper mentioned above. The stack is so simple!
Although the reverse polish expression looks complicated, it is actually very useful in computers. The computer does not know how to multiply, multiply, add, and subtract. It must enclose the brackets and then parentheses. It must convert the formula you entered into a reverse polish expression, so that it can continue to execute the above two rules, until the result is displayed. Now you can try it on your computer and try to compile a program, read it into a reverse polish expression, and then let it calculate it!
Succeeded? If you answer "yes", you can continue to think about another question, for the sequence of 7 elements 1 2 3 4 5 6 7, after processing a stack (for example, 1 2 3 into the stack, 3 2 pop up, 4 into the stack, 4 pop up ...... And so on), how many different sorting types can be obtained? Can we get 4 3 5 2 1 7 6? Can we get 3 2 4 5 7 1 6?