Inverse Polish expression (recursive + struct-body function)

Source: Internet
Author: User


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)

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.