前缀表达式的求值
来源:互联网 发布:叁度软件破解版 编辑:程序博客网 时间:2024/05/24 03:41
前面发了中缀表达式和后缀表达式的求值方法,在这儿,前缀表达式也差不多
#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;
}
0 0
- 前缀表达式的求值
- 前缀表达式求值的递归程序
- 前缀表达式求值
- 前缀表达式求值
- 前缀表达式求值
- 前缀表达式求值--栈
- 前缀式表达式求值
- 前缀,中缀,后缀表达式的转换,表达式的求值
- 中缀表达式求值、后缀表达式求值、中缀转后缀、前缀
- 前缀表达式求值(Prefix expressions)
- 表达式求值(前缀、中缀、后缀)
- 中缀、前缀和后缀表达式求值问题
- 前缀 中缀 后缀 表达式求值问题
- NYOJ128--前缀表达式求值--递归版
- 算术表达式转成前缀表达式(波兰表达式)并求值
- 前缀表达式求值 后缀表达式求值 中缀表达式转后缀表达式
- VS2015,C++实现前缀、中缀、后缀表达式求值、前缀转中缀、前缀转后缀。
- 表达式求值的问题
- 选择排序-【堆排序】
- C++primer第5版课后练习习题答案7.23
- 下载provinces_cities.plist
- hdu 4054 模拟 练习十六进制输出
- 三大框架之Hibernate
- 前缀表达式的求值
- Populating Next Right Pointers in Each Node II
- JQuery实现图片轮换
- Matlab程序转C++/OpenCV不可不知的17个函数
- 计算表达式的值c++逆波兰式实现方法
- Leetcode:unique_binary_search_trees
- Codeforces Bayan Bus
- iOS笔记--多点触碰的时候如何获取其中的某一次点击事件
- linux下fflush(stdin)的使用问题