用栈计算表达式

来源:互联网 发布:ubuntu设置网络连接 编辑:程序博客网 时间:2024/06/05 20:11

首先声明我们的表达式(expression)只是简单的四则运算,再加上小括号.

操作数operand,操作符operator

如果直接给出后缀表达式(postfix,也叫逆波兰式)是最容易计算的,这种表达式中已经不含括号.方法:遇到操作数时压入栈中;遇到操作符时从栈中弹出两个元素进行此运算,再将运算结果压入栈中.代码如下:

#include<iostream>#include<cstdlib>#include<stack>#include<vector>#include<string>using namespace std;int main(){string postfix[]={"4.99","1.06","*","5.99","+","6.99","1.06","*","+"};stack<float> s;string opt="+-*/";size_t len=sizeof(postfix)/sizeof(string);for(int i=0;i<len;i++){string ele=postfix[i];if(string::npos==opt.find(ele)){float e=atof(ele.c_str());s.push(e);}else{float a=s.top();s.pop();float b=s.top();s.pop();int index=opt.find(ele);switch(index){case 0:s.push(a+b);break;case 1:s.push(a-b);break;case 2:s.push(a*b);break;case 3:s.push(a/b);break;}}}cout<<s.top()<<endl;return 0;}

但通常我们看到的形式都是中缀表达式,形如:a+b*c-(d*e+f)/g

我们可以先把中缀表达式转换成后缀表达式再进行运算

#include<stack>#include<queue>#include<string>#include<iostream>using namespace std;bool not_prio_than(string opt1,string opt2);int main(){//中缀表达式string infix[]={"a","+","b","*","c","-","(","d","*","e","+","f",")","/","g"};//a+b*c-(d*e+f)/g//所有运算符string opt="+-*/()";//输出队列queue<string> output;//计算过程中用到的栈stack<string> st;size_t len=sizeof(infix)/sizeof(string);for(int i=0;i<len;i++){//取出中缀表达式中的当前元素string ele=infix[i];//如果当前元素不是运算符if(string::npos==opt.find(ele)){output.push(ele);}//如果当前元素是右括号else if(ele==")"){string stop=st.top();//从栈中弹出元素放入输出队列中,直到遇到左括号为止while(stop!="("){st.pop();output.push(stop);if(st.empty())break;stop=st.top();}//左括号出栈,但并不放入队列if(stop=="(")st.pop();}//如果当前元素是除右括号以外的运算符else{if(!st.empty()){string stop=st.top();//如果当前元素(是运算符)不比栈顶元素优先级别高,则弹出栈顶元素,并放入输出队列中//除非正在处理右括号,否则左括号不会从栈中弹出while(stop!="("&¬_prio_than(ele,stop)){st.pop();output.push(stop);if(st.empty())break;stop=st.top();}}//当前元素入栈st.push(ele);}}//当输入为空时,把栈中剩余的元素全部弹出,放到输出队列中while(!st.empty()){string top=st.top();output.push(top);st.pop();}//打印输出队列while(!output.empty()){cout<<output.front();output.pop();}cout<<endl;}bool not_prio_than(string opt1,string opt2){//运算符优先级string prio_1="()";string prio_2="*/";string prio_3="+-";//数字表示两个参数的优先级int a,b;if(string::npos!=prio_1.find(opt1))a=1;else if(string::npos!=prio_2.find(opt1))a=2;else if(string::npos!=prio_3.find(opt1))a=3;if(string::npos!=prio_1.find(opt2))b=1;else if(string::npos!=prio_2.find(opt2))b=2;else if(string::npos!=prio_3.find(opt2))b=3;return a>=b?true:false;}

原创粉丝点击