Title: Inverse Polish expression
The normal expression is called infix expression, operator in the middle, mainly for people to read, the machine is not easy to solve.
Example: 3 + 5 * (2 + 6)-1
Also, it is often necessary to use parentheses to change the order of operations.
Conversely, if you use an inverse Polish expression (a prefix expression), the above calculation is represented as:
-+ 3 * 5 + 2 6 1
Brackets are no longer needed, and the machine can be easily solved by recursive methods.
For simplicity, we assume that:
1. Only +-* Three kinds of operators
2. Each operand is a non-negative integer less than 10
The following program evaluates a string that is inverted to Poland.
Its return value is a structure where the first element represents the evaluation result, and the second element represents the number of characters it has resolved.
#include <stdio.h> #include <string.h> #include <string> #include <math.h> #include < stdlib.h> #include <time.h> #include <iostream> #include <algorithm>using namespace std; #define N 100000#define ll Long long#define mem (a,t) memset (A,t,sizeof (a)) const double eps=1e-10;struct ev{int result; calculation result int n; Number of characters consumed}ans;struct ev evaluate (char* x) {struct EV ev = {0,0};struct ev v1;struct EV v2;if (*x==0) return ev;if (x[0]>= ' 0 ' && x[0]<= ' 9 ') {ev.result = x[0]-' 0 '; EV.N = 1;return ev;} V1 = Evaluate (x+1); v2 = Evaluate (x+v1.n+1);//_____________________________; Fill-in position if (x[0]== ' + ') Ev.result = V1.result + v2.result;if (x[0]== ' * ') Ev.result = V1.result * V2.RESULT;IF (x[0]== '-') ev.re Sult = V1.RESULT-V2.RESULT;EV.N = 1+v1.n+v2.n;return ev;} int main () {//freopen ("In.txt", "R", stdin),//freopen ("OUT.txt", "w", stdout), char s[]={"-+3*5+261"};ans=evaluate (s); printf ("%d\n", Ans.result);//printf ("%d%d\n", i,i*i); return 0;}
Inverse Polish expression (recursive + struct-body function)