C++ inverse Polish

  • 2020-11-20 06:11:29
  • OfStack

(a+b) The inverse polish of c is ab+c. Assuming that the computer presses ab+c on the stack in order from left to right, and carries out the processing according to the principle of pushing the top two elements out of the stack when it encounters an operator, then the result of the execution of ab+c is as follows:

1) a push (position 0)
2) b push (position 1)
3) When the operator "+" is encountered, push a and b out of the stack, perform the operation of a+b, and get the result d=a+b, then push d on the stack (position 0).
4) c push (position 1)
5) When the operator "" is encountered, push d and c out of the stack, perform the operation of dc, get the result of e, and then push e onto the stack (position 0)

After the above calculation, the computer can get the result of (a+b)*c.

In addition to implementing the above types of operations, inverse Polish can also derive many new algorithms, data structures, which need to be used flexibly. Inverse Polish is just one form of sequential representation.

eg:

The input sample

[

1 2 + 3 4 - *

]

Sample output

[

-3

]

code


#include <iostream>
#include <stack>
#include <cstdio>
using namespace std;

int main()
{
 string s;
 getline(cin,s);
 int n = s.length();// String length 
 stack<int> t;
 for(int i=0;i<n;i++)
 {
 char c=s[i];
 if(c=='+'){
 int a=t.top();
 t.pop();
 int b=t.top();
 t.pop();
 t.push(a+b);
 }
 else if(c=='-'){
 int a=t.top();
 t.pop();
 int b=t.top();
 t.pop();
 t.push(b-a);
 }
 else if(c=='*'){
 int a=t.top();
 t.pop();
 int b=t.top();
 t.pop();
 t.push(a*b);
 }
 else if(c=='/'){
 int a=t.top();
 t.pop();
 int b=t.top();
 t.pop();
 t.push(a/b);
 }
 else if(c==' '){
 continue;
 }
 else{// digital 
 int m=(int)c;
 m=m-48;
 t.push(m);
 }
 }

 cout<<t.top();

 return 0;
}

Related articles: