Topic Links:
Prefix expression evaluation
Exercises
Evaluation ideas with suffix expressions:
Encountered the value of the stack, encountered the operator from the stack to remove the top two values to operate, then the results into the stack, the final stack of the top element is the answer.
The prefix expression is traversed from the back forward.
Code:
#include <iostream> #include <cstdio> #include <cstring> #include <stack>using namespace std; int op (char a) {if (a== ' + ' | | a== '-' | | a== ' * ' | | a== '/') return 1; return 0;} int main () {char str1[105]; int len,i,flag=0,k=1,flagg=0; Double s=0; Gets (STR1); Len=strlen (STR1); stack<double>q; for (i=len-1; i>=0; i--)//from backwards {if (str1[i]== ') {if (s!=0) Q.pu SH (s); flag=0,s=0,k=1; } else if (flag==0&&str1[i]>= ' 0 ' &&str1[i]<= ' 9 ') flag=1,s=str1[i]-' 0 ', k=k*10; else if (flag==1&&str1[i]>= ' 0 ' &&str1[i]<= ' 9 ') s=s+ (str1[i]-' 0 ') *k,k=k*10; else if (flag==1&&str1[i]== '-') s=-s; else if (flag==1&&str1[i]== '. ') s=s/100.0,k=1; else if (Flag==0&&op (Str1[i])) {double A,b,ans; A=q.top (); Q.Pop (); B=q.top (); Q.pop (); if (str1[i]== ' + ') ans=a+b; else if (str1[i]== '-') ans=a-b; else if (str1[i]== ' * ') ans=a*b; else if (str1[i]== '/') {if (b==0)//divisor is 0 is error flagg=1 ; ans=a/b; } q.push (ANS); }} if (Q.empty ())//Last set of sample Q.push (s); if (flagg==1| | Q.size () >1) printf ("error\n"); else printf ("%.1lf\n", Q.top ()); return 0;}
PAT linear structure 3. Application of value stack for prefix expression