前面发了中缀表达式和后缀表达式的求值方法,在这儿,前缀表达式也差点儿相同
#include<iostream>
#include<stack>#include<string>
using namespace std;
int judge(char popx,char x);
int func(string String,int *i);
int calculate(int x,int y,char str);
int main()
{
int n,i;
string a;
stack<char>str;
str.push('#');
cin>>n;
while(n--)
{
cin>>a;
string substr="";
int j;
for(i=a.length()-1;i>=0;)
{
if(a[i]-'0'>=0&&a[i]-'0'<=9)
{
for(j=i;a[j]-'0'>=0&&a[j]-'0'<=9;j--)
substr+=a[j];
substr+=' ';
i=j;
}
else
{
if(judge(str.top(),a[i])==2) //出栈
{
substr+=str.top();
str.pop();
}
else
if(judge(str.top(),a[i])==1) //入栈
{
str.push(a[i]);
i--;
}
else
if(judge(str.top(),a[i])==4)
{
str.pop();
i--;
}
else
if(judge(str.top(),a[i])==3)
{
substr+=str.top();
str.pop();
}
}
}
while(str.top()!='#')
{
substr+=str.top();
str.pop();
}
stack<int>num;
string a=substr;
for(i=0;i<a.length();)
{
if((a[i]-'0'>=0&&a[i]-'0'<=9))
{
int numm=0;
for(j=i;(a[j]-'0'>=0&&a[j]-'0'<=9);j++)
;
for(int k=j-1;k>=i;k--)
numm=numm*10+a[k]-'0';
num.push(numm);
i=j;
}
else if(a[i]!=' ')
{
int num1=num.top();
num.pop();
int num2=num.top();
num.pop();
num.push(calculate(num1,num2,a[i]));
i++;
}
else
if(a[i]==' ')
i++;
}
cout<<num.top()<<endl;
num.pop();
}
}
int judge(char popx,char x)
{
if(popx=='*'||popx=='/')
{
if(x=='*'||x=='/'||x==')') //入栈
return 1;
else
if(x=='+'||x=='-')
return 2; //出栈继续算
else
if(x=='(')
return 3; //出栈计算
}
else
if(popx=='+'||popx=='-')
{
if(x=='*'||x=='/'||x=='+'||x=='-'||x==')')
return 1;
if(x=='(')
return 3;
}
else
if(popx==')'&&x!='(')
return 1;
else
if(popx==')'&&x=='(')
return 4; //出栈后移
else
if(popx=='#')
return 1;
}
int calculate(int x,int y,char str)
{
if(str=='+')
return x+y;
else
if(str=='-')
return x-y;
else
if(str=='*')
return x*y;
else
if(str=='/')
return x/y;
}
int func(string String,int *i)
{
int j,num=0;
for(j=*i;String[j]-'0'>=0&&String[j]-'0'<=9&&String[j]!=' ';j++)
{
num=num*10+(String[j]-'0');
}
*i=j;
return num;
}