码迷,mamicode.com
首页 > 其他好文 > 详细

前缀表达式的求值

时间:2014-10-06 00:58:29      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:数据结构   iostream      

前面发了中缀表达式和后缀表达式的求值方法,在这儿,前缀表达式也差不多

#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;
}



前缀表达式的求值

标签:数据结构   iostream      

原文地址:http://blog.csdn.net/u013412497/article/details/39807493

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!