栈应用之计算全括号形式的数值表达式

来源:互联网 发布:软件如何申请专利 编辑:程序博客网 时间:2024/05/22 14:11

1.判断表达式括号是否配对

#include <iostream>#include <stack>using namespace std;bool isBalanced(const string& expression) {const char left = '(', right = ')';bool flag = true;stack<char> chstack;char ch;for(int i = 0; i < expression.size(); i++) {ch = expression[i];if(ch == '(')chstack.push(ch);else if(ch == ')' && !chstack.empty())chstack.pop();else if(ch == ')' && chstack.empty()) {flag = false;break;}}return (chstack.empty() && flag);}

2.计算数值表达式

使用条件:(1)表达式使用全括号形式,中缀表达式 (2)表达式中只能出现‘+’、‘-’、‘*’、‘/'等二元操作符,不能出现取反等一元操作符,即为非负数

#include <iostream>#include <stack>#include <cctype> using namespace std;void evaluate_top(stack<double>& nums, stack<char>& operations) {double operd2 = nums.top();nums.pop();double operd1 = nums.top();nums.pop();switch(operations.top()) {case '+' : nums.push(operd1 + operd2);break;case '-' : nums.push(operd1 - operd2);break;case '*' : nums.push(operd1 * operd2);break;case '/' : nums.push(operd1 / operd2);break;}operations.pop();}double read_and_evaluate(istream &ins) {stack<char> chstack;stack<double> dstack;const char DECIMAL = '.', RIGHT_PAR = ')';double num;char ch;while(ins && ins.peek()!='\n') {if(isdigit(ins.peek()) || ins.peek() == DECIMAL) {ins >> num;dstack.push(num);}else if((ins.peek() == '+') || (ins.peek() == '-') || (ins.peek() == '*') || (ins.peek() == '/')) {ins >> ch;chstack.push(ch);}else if(ins.peek() == RIGHT_PAR) {ins.ignore();evaluate_top(dstack, chstack);}else ins.ignore();}return dstack.top();}int main() {cout << "Type a fully parethesized arithmetic expression:" << endl;double result = read_and_evaluate(cin);cout << "That evaluates to " << result << endl;return 0;}


0 0
原创粉丝点击