逆波兰表达式实现
2017-01-12 10:48
253 查看
#include<iostream> #include<stack> using namespace std; //把一个算式先转化为逆波兰表达式 int Priority(char ch)//定义优先级别 { int i; switch (ch) { case'(':i = 1; break; case'+':i = 2; break; case'-':i = 2; break; case'*':i = 4; break; case'/':i = 4; break; case')':i = 5; break;//优先级最高 default:i = -1; break; } return i; } void tonibolan(char *ch, char retch[100]) { stack<char> st2; int i = 0; while (*ch != '\0') { if (*ch >= '0'&&*ch <= '9') retch[i++] = *ch; else if (*ch == '(')//左括号直接压栈 ,不考虑优先级 st2.push(*ch); else if (*ch == ')')//找到匹配的左括号 { while (st2.top() != '(') { retch[i++] = st2.top(); st2.pop(); } st2.pop(); } else if (st2.empty() || Priority(*ch)>Priority(st2.top())) st2.push(*ch); else { while (Priority(*ch) <= Priority(st2.top())) { retch[i++] = st2.top(); st2.pop(); if (st2.empty()) break; } st2.push(*ch); } ch++; } while (!st2.empty()) { retch[i++] = st2.top(); st2.pop(); } retch[i] = 0; } //计算逆波兰表达式的值 int calcval(char *ret) { stack<char> st; while (*ret != '\0') { if (*ret >= '0'&&*ret <= '9') st.push(*ret);//数字直接入栈 else { switch (*ret) { case'+': { char a = st.top(); st.pop(); char b = st.top(); st.pop(); st.push(((a - '0') + (b - '0') + '0'));//注意类型的运算 break; } case'-': { char a = st.top(); st.pop(); char b = st.top(); st.pop(); st.push(((b - '0') - (a - '0')) + '0'); break; } case'*': { char a = st.top(); st.pop(); char b = st.top(); st.pop(); st.push(((b - '0')*(a - '0')) + '0'); break; } case'/': { char a = st.top(); st.pop(); char b = st.top(); st.pop(); if (a != '0') { st.push((((b - '0') / (a - '0')) + '0')); } else { cout << "除数为0错误" << endl; } break; } } } ret++; } return st.top() - '0'; } int main() { char c; int i = 0; char ret[100] = {'\0'}; char ch[100] = {'\0'}; while (cin >> c) ch[i++] = c; tonibolan(ch, ret); i = 0; cout << "算式的逆波兰表达式为:" << endl; while (ret[i]!='\0') { cout << ' ' << ret[i++]; } cout << "\n算式的计算结果为:" << endl; cout << calcval(ret) << endl; system("pause"); return 0; }
相关文章推荐
- 递归实现逆波兰式到正常表达式的转换
- 一个逆波兰表达式实现的四则混合运算计算器
- 如何用程序实现逆波兰表达式值算法问题
- 栈实现逆波兰表达式
- 栈_逆波兰表达式_计算器实现_Golang版本
- 堆栈的应用(2) 中缀算术表达式到后缀(逆波兰记法reverse polish notation)的转换及其计算 C++实现
- 实现四则运算——逆波兰表达式
- 逆波兰表达式的c++实现
- MFC计算器 用vector实现和计算逆波兰表达式
- python实现逆波兰计算表达式实例详解
- 【原创】Delphi实现数学表达式的计算(逆波兰式法)-四则运算解析
- php简单实现算术表达式转换成逆波兰式,并求解
- 24点算法 | 逆波兰表达式实现去重复
- 计算表达式的值c++逆波兰式实现方法
- java使用栈和逆波兰表达式实现四则运算
- 逆波兰表达式算法实现
- 【晨哥的C语言之旅】逆波兰表达式实现计算器功能
- C指针原理(32)-编译原理-逆波兰表达式及其实现
- android逆波兰表达式的应用(四)逆波兰表达式的计算实现 -----小达
- C语言实现逆波兰表达式