juyana

zz

Jul 2nd, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define mx 10000
  5.  
  6.  
  7. int a[mx];
  8. int tp=-1;
  9.  
  10. int Push(int x)
  11. {
  12. if(tp==mx-1)
  13. {
  14. cout<<"Stack overflow"<<endl;
  15. return 0;
  16. }
  17. else
  18. a[++tp]=x;
  19. }
  20. void Pop()
  21. {
  22. if(tp==mx-1)
  23. {
  24. cout<<"No element to print"<<endl;
  25. return;
  26. }
  27. tp--;
  28. }
  29. int Top()
  30. {
  31. return a[tp];
  32. }
  33. bool Empty()
  34. {
  35. if(tp==-1)
  36. return true;
  37. else return false;
  38. }
  39.  
  40. bool isoperator(char c)
  41. {
  42. if(c=='+'||c=='-'||c=='/'||c=='*')
  43. return true;
  44. return false;
  45. }
  46. bool isoperand(char c)
  47. {
  48. if((c>='0'&&c<='9')||(c>='a'&&c<='z')||(c>='A'&&c<='Z'))
  49. return true;
  50. return false;
  51. }
  52. int perform(char c,int o1,int o2)
  53. {
  54. switch(c)
  55. {
  56. case '+':
  57. return o1+o2;
  58. case '-':
  59. return o1-o2;
  60.  
  61. case '*':
  62. return o1*o2;
  63. case '/':
  64. return o1/o2;
  65. }
  66. }
  67. int prefix_evaluation(string s)
  68. {
  69. int op1,op2,result;
  70. for(int i=s.size()-1; i>=0; i--)
  71. {
  72. if(s[i]==' '||s[i]==',') continue;
  73. else if(isoperand(s[i]))
  74. {
  75. int operand=0,x=1;
  76. while(i<s.size()&&isoperator(s[i]))
  77. {
  78. operand=operand+(s[i]-'0')*x;
  79. i--;
  80. x*=10;
  81. }
  82. Push(operand);
  83. i++;
  84. }
  85. else if(isoperator(s[i]))
  86. {
  87. op1=Top(); Pop();
  88. op2=Top(); Pop();
  89. result= perform(s[i],op1,op2);
  90. Push(result);
  91. }
  92. }
  93. return Top();
  94. }
  95.  
  96. int main()
  97. {
  98. string s;
  99. getline(cin,s);
  100. int x= prefix_evaluation(s);
  101. cout<<"result= "<<x<<endl;
  102. /**
  103. - + * 2 3 * 5 4 9
  104. **/
  105. }
Advertisement
Add Comment
Please, Sign In to add comment