在C++中使用栈来把中缀表达式转换为后缀表达式并求值,简单明了
2016-07-12 18:31
369 查看
#include<iostream>
#include<stdlib.h>//头文件包含atoi()函数
using namespace std;
typedef char T;
class stack{
T data[100];
int sz;
public:
stack() :sz(){}
void push(const T& d){
if (full()) throw "满";
data[sz++] = d;
}
void pop(){
if (empty()) throw "空";
sz--;
}
T top(){
if (empty()) throw"空";
return data[sz - 1];
}
T undertop(){
if (empty()) throw"空";
return data[sz-2];
}
int Ssz(){//返回栈的元素数量
return sz;
}
char Sdata(const int i){//返回栈相应位置的元素,栈低为位置0
return data[i];
}
bool empty(){ return sz == 0; }
bool full(){ return sz == 100; }
};
//c1高于c2返回true,否则返回false
bool prior(char c1, char c2){
return (c1 == '*' || c1 == '/') && (c2 == '+' || c2 == '-');
}
int main()
{
string str = "1+4";
stack res;//结果栈
stack exp;//运算栈
stack cres;//计算结果栈
stack num;//计算运算栈
char ch;
for (int i = 0; i<str.length(); i++){
ch = str[i];
if (ch >= '0'&&ch <= '9'){//是数字的话就把ch放入res结果栈中
res.push(ch);
}
else if ('(' == ch){
exp.push(ch);
}
else if (')' == ch){
while (exp.top() != '('){
res.push(exp.top());
exp.pop();
}
exp.pop();
}
else{//是运算符
while (!exp.empty() && exp.top() != '('//当exp运算栈不为空且栈顶元素不为'('且ch优先级低于或等于栈顶元素
&&!prior(ch, exp.top())){
res.push(exp.top());
exp.pop();
}
exp.push(ch);
}
}
while (!exp.empty()){
res.push(exp.top());
exp.pop();
}
cres=res;
while (!res.empty()){
cout << res.top();
res.pop();
}
cout << endl;
cout<<"-----------------"<<endl;
for(int i=0;i<cres.Ssz();i++){
if(cres.Sdata(i)>='0'&&cres.Sdata(i)<='9'){//如果是数字就放入数字栈
num.push(cres.Sdata(i));
}
else if(cres.Sdata(i)=='*'){//如果符号是乘号
// a=atoi(num.top())*atoi(num.undertop());//atoi()把字符串转化为整形数
int a=(num.undertop()-48/*或者0*/)*(num.top()-48/*或者0*/);//字符减去48就转化成int型
char c=a+'0'; //int型加上'0'就转化为char型
num.pop();
num.pop();
num.push(c);
}
else if(cres.Sdata(i)=='/'){
int a=(num.undertop()-48)/(num.top()-48/*或者0*/);
char c=a+'0';
num.pop();
num.pop();
num.push(c);
}
else if(cres.Sdata(i)=='+'){
int a=(num.undertop()-48/*或者0*/)+(num.top()-48/*或者0*/);
char c=a+'0';
num.pop();
num.pop();
num.push(c);
}
else if(cres.Sdata(i)=='-'){
int a=(num.undertop()-48/*或者0*/)-(num.top()-48/*或者0*/);
char c=a+'0';
num.pop();
num.pop();
num.push(c);
}
}
cout<<num.top()<<endl;
}
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析
- C与C++之间相互调用实例方法讲解