用栈计算表达式
来源:互联网 发布: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;}
- 用栈计算表达式
- 表达式计算 用栈完成
- 用栈实现表达式计算
- C++用栈计算表达式
- 用栈实现表达式计算
- C++实现:用栈实现表达式计算
- 表达式计算之一:栈
- 栈应用---计算表达式
- 栈实现表达式计算
- 栈计算表达式
- 计算表达式(栈)
- 栈计算表达式
- 计算表达式 栈
- 表达式计算栈实现
- 表达式计算(栈)
- 用 树 计算 表达式
- 表达式计算,输出后缀表达式,栈实现
- 利用双栈计算表达式
- Qt4--FormLayout
- linux下用dnw烧写文件系统
- ubuntu上安装CLucene
- 利用不相交集画迷宫
- command>/dev/null 2>&1
- 用栈计算表达式
- 由二叉树的先序中序推出后序
- 最大子序列、最长递增子序列、最长公共子串、最长公共子序列、字符串编辑距离
- 开源软件许可协议简介
- 最小生成树--Prim和Kruskal算法
- MySQL中文支持
- 串的模式匹配
- 邻接表存储图,深度和广度优先遍历
- 位图散列