【栈】一个简答的四则运算计算器的实现
2015-03-22 22:34
573 查看
题目:输入一个中缀表达式的字符串,出去表达式的结果(只考虑整数)。
主要思路为先用栈把中缀表达式转换为后缀表达式,然后计算后缀表达式的值。
主要思路为先用栈把中缀表达式转换为后缀表达式,然后计算后缀表达式的值。
char * InfixToPostfix(char *s) { if (s == NULL) return NULL; stack<char> st; stack<char> post; char *p = s; int priority[256] = {0}; //设置运算符优先级 priority['+'] = 0; priority['-'] = 0; priority['*'] = 1; priority['/'] = 1; priority['('] = -1; while (*p != '\0') { if (*p >= '0' && *p <= '9') { post.push(*p++); } else if (*p == '(') { st.push(*p++); } else if (*p == ')') { while (!st.empty() && st.top() != '(') { post.push(st.top()); st.pop(); } st.pop(); //‘(’出栈 ++p; } else { while (!st.empty() && priority[st.top()] >= priority[*p]) { post.push(st.top()); st.pop(); } st.push(*p++); } } while (!st.empty()) { post.push(st.top()); st.pop(); } while (!post.empty()) { st.push(post.top()); post.pop(); } int len = strlen(s); char *res = new char[len + 1]; int i = 0; while (!st.empty()) { res[i++] = st.top(); st.pop(); } res[i] = '\0'; return res; } int BinaryComp(int a, int b, char c) { switch (c) { case '*': return a * b; break; case '+': return a + b; break; case '-': return a - b; break; case '/': return a /b; break; default: break; } } int CalCul(char *s) { if (s == NULL) return 0; stack<int> st; while (*s != '\0') { if (*s >= '0' && *s <='9') { st.push(*s - '0'); ++s; } else { int a = st.top(); st.pop(); int b = st.top(); st.pop(); int res = BinaryComp(a, b, *s); s++; st.push(res); } } return st.top(); }
相关文章推荐
- php实现一个简单的四则运算计算器
- 利用ANTLR4实现一个简单的四则运算计算器
- 一个逆波兰表达式实现的四则混合运算计算器
- 使命栈(stack)实现一个简易的四则运算计算器
- 设计一个计算器类Calculator,它只有一个计数的成员count。该计算器的有效范围说0~65535,实现计算器的前自增、后自增、前自减、后自减、两个计算器相加减等运算
- VC++.NET中用类实现带科学计数法的四则运算计算器(有完整的代码哦)(2005-05-08)
- 习题10:参照Windows系统“附件”中的“计算器”,自行编写一个简易的计算器。要求:可以实现由0~4构成的整数的加减运算。
- 栈 实现四则运算的计算器
- JavaScript实现简单的四则运算计算器完整实例
- QT,计算器实现(四则运算,括号,小数,负数)---(一)
- 用位运算实现四则运算之加减乘除(用位运算求一个数的1/3)
- JS实现的简单四则运算计算器功能示例
- 算法--两种方法实现一个Add函数,让两个整数相加,但是不能使用+、-、*、/等四则运算符。
- 正则表达式实现的加减乘除四则运算的计算器
- 用位运算实现四则运算之加减乘除(用位运算求一个数的1/3)
- 学习C++的成果,一个简单的四则运算计算器内核
- Java写的一个计算器(用堆栈实现复杂运算)
- Java实现四则运算计算器
- 利用java的swing控件实现四则混合运算计算器
- 实现一个Add函数,让两个数相加,但是不能使用+、-、*、/等四则运算符。ps:也不能用++、--等等