中缀表达式的值

来源:互联网 发布:淘宝中老年女加绒棉袄 编辑:程序博客网 时间:2024/06/05 19:11

5:中缀表达式的值

  • 查看
  • 提交
  • 统计
  • 提问
总时间限制: 
200ms 
内存限制: 
1024kB
描述
人们熟悉的四则运算表达式称为中缀表达式,例如(23+34*45/(5+6+7))。在程序设计语言中,可以利用堆栈的方法把中缀表达式转换成保值的后缀表达式(又称逆波兰表示法),并最终变为计算机可以直接执行的指令,得到表达式的值。

给定一个中缀表达式,编写程序,利用堆栈的方法,计算表达式的值。
输入
第一行为测试数据的组数N
接下来的N行,每行是一个中缀表达式。表达式中只含数字、四则运算符和圆括号,操作数都是正整数,数和运算符、括号之间没有空格。中缀表达式的字符串长度不超过600。
输出
对每一组测试数据输出一行,为表达式的值
样例输入
33+5*8(3+5)*8(23+34*45/(5+6+7))
样例输出
4364108
提示
注意:运算过程均为整数运算(除法运算'/'即按照C++定义的int除以int的结果,测试数据不会出现除数为0的情况),输出结果也为整数(可能为负)。
中间计算结果可能为负。

#include<iostream>#include<cmath>#include<cstring>#include<algorithm>#include<iomanip>#include<queue>#include<stack>#include<vector>#include<set>#include<map>using namespace std;stack<int>S1;stack<char>S2;int main(){int Test;cin>>Test;cin.get();while(Test--) {while(!S1.empty())S1.pop();while(!S2.empty())S2.pop();char c=cin.peek();while(c!='\n') {if(c>='0'&&c<='9'){int a;cin>>a;S1.push(a);}else if(c=='('){cin>>c;S2.push(c);}else if(c==')'){cin>>c;while(S2.top()!='('){char s=S2.top(); S2.pop();int tmp1=S1.top(); S1.pop();int tmp2=S1.top(); S1.pop();if(s=='+'){S1.push(tmp2+tmp1);}if(s=='-'){S1.push(tmp2-tmp1);}if(s=='*'){S1.push(tmp2*tmp1);}if(s=='/'){S1.push(tmp2/tmp1);}}S2.pop();}else if(c=='+'||c=='-'){cin>>c;while(!S2.empty()&&S2.top()!='('){char s=S2.top(); S2.pop();int tmp1=S1.top(); S1.pop();int tmp2=S1.top(); S1.pop();if(s=='+'){S1.push(tmp2+tmp1);}if(s=='-'){S1.push(tmp2-tmp1);}if(s=='*'){S1.push(tmp2*tmp1);}if(s=='/'){S1.push(tmp2/tmp1);}}S2.push(c);}else if(c=='*'||c=='/'){cin>>c;while(!S2.empty()&&(S2.top()=='*'||S2.top()=='/')){char s=S2.top(); S2.pop();int tmp1=S1.top(); S1.pop();int tmp2=S1.top(); S1.pop();if(s=='*'){S1.push(tmp2*tmp1);}if(s=='/'){S1.push(tmp2/tmp1);}}S2.push(c);}c=cin.peek();}cin.get();while(!S2.empty()){char s=S2.top(); S2.pop();int tmp1=S1.top(); S1.pop();int tmp2=S1.top(); S1.pop();if(s=='+'){S1.push(tmp2+tmp1);}if(s=='-'){S1.push(tmp2-tmp1);}if(s=='*'){S1.push(tmp2*tmp1);}if(s=='/'){S1.push(tmp2/tmp1);}}cout<<S1.top()<<endl; }return 0;}