Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- #define mx 10000
- int a[mx];
- int tp=-1;
- int Push(int x)
- {
- if(tp==mx-1)
- {
- cout<<"Stack overflow"<<endl;
- return 0;
- }
- else
- a[++tp]=x;
- }
- void Pop()
- {
- if(tp==mx-1)
- {
- cout<<"No element to print"<<endl;
- return;
- }
- tp--;
- }
- int Top()
- {
- return a[tp];
- }
- bool Empty()
- {
- if(tp==-1)
- return true;
- else return false;
- }
- bool isoperator(char c)
- {
- if(c=='+'||c=='-'||c=='/'||c=='*')
- return true;
- return false;
- }
- bool isoperand(char c)
- {
- if((c>='0'&&c<='9')||(c>='a'&&c<='z')||(c>='A'&&c<='Z'))
- return true;
- return false;
- }
- int perform(char c,int o1,int o2)
- {
- switch(c)
- {
- case '+':
- return o1+o2;
- case '-':
- return o1-o2;
- case '*':
- return o1*o2;
- case '/':
- return o1/o2;
- }
- }
- int prefix_evaluation(string s)
- {
- int op1,op2,result;
- for(int i=s.size()-1; i>=0; i--)
- {
- if(s[i]==' '||s[i]==',') continue;
- else if(isoperand(s[i]))
- {
- int operand=0,x=1;
- while(i<s.size()&&isoperator(s[i]))
- {
- operand=operand+(s[i]-'0')*x;
- i--;
- x*=10;
- }
- Push(operand);
- i++;
- }
- else if(isoperator(s[i]))
- {
- op1=Top(); Pop();
- op2=Top(); Pop();
- result= perform(s[i],op1,op2);
- Push(result);
- }
- }
- return Top();
- }
- int main()
- {
- string s;
- getline(cin,s);
- int x= prefix_evaluation(s);
- cout<<"result= "<<x<<endl;
- /**
- - + * 2 3 * 5 4 9
- **/
- }
Advertisement
Add Comment
Please, Sign In to add comment