栈的应用:表达式求值运算
Posted yoyo_sincerely
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了栈的应用:表达式求值运算相关的知识,希望对你有一定的参考价值。
http://blog.csdn.net/wenzhou1219/article/details/23961307
#include <iostream> #include <cstdio> #include <stack> #include <cstring> #include <stdlib.h> using namespace std; #define LEVEL_invalid -1 #define LEVEL_same 0 #define LEVEL_smaller 1 #define LEVEL_bigger 2 stack <char> ops,mid_ops; stack <double> vals,mid; double m,n; char operator_level_1[10] = {‘#‘, ‘(‘, ‘+‘, ‘-‘, ‘*‘, ‘/‘, ‘)‘}; char operator_level_2[10] = {‘#‘, ‘)‘, ‘-‘, ‘+‘, ‘/‘, ‘*‘, ‘(‘}; int compare_operator(char op1, char op2){ int level1_index1 = -1,level1_index2 = -1; int level2_index1 = -1,level2_index2 = -1; if((op1 == ‘)‘ && op2 == ‘(‘) || (op1 == ‘#‘ && op2 == ‘)‘) || (op1 == ‘(‘ && op2 == ‘#‘))///)和(, #和),(和#都是不能配对的,不合法; return LEVEL_invalid; if((op1 == ‘(‘ && op2 == ‘)‘) || (op1 == ‘#‘ && op2 == ‘#‘)) return LEVEL_same; while(operator_level_1[++level1_index1] != op1); ///op1 在 level_1中的位置大小; while(operator_level_1[++level1_index2] != op2); ///op2 在 level_1中的位置大小; while(operator_level_2[++level2_index1] != op1); ///op1 在 level_2中的位置大小; while(operator_level_2[++level2_index2] != op2); ///op2 在 level_2中的位置大小; ///1.判断两个操作符的优先级关系 ///2.‘#‘ < ‘+‘, ‘-‘ < ‘*‘, ‘/‘ ///3.两个相同的运算符或同级别的运算符(‘+‘和‘-‘,‘*‘和‘/‘) ///对比时应判定为前一个运算符优先级别高,这样才能保证连续 ///两个相同的运算符或同级别的运算符出现时前一个运算符出栈 ///完成一次计算 if((level1_index1 - level1_index2 <0 && level2_index1 - level2_index2 <0)||op1 == ‘(‘ || op2 == ‘(‘) return LEVEL_smaller; else return LEVEL_bigger; } void cal_operator(char op2){ char op1 = ops.top(); int result = compare_operator(op1, op2); if(result == LEVEL_smaller) ops.push(op2); else if(result == LEVEL_same) ops.pop(); else if(result == LEVEL_bigger){ char s = ops.top();ops.pop(); double n,m; m = vals.top();vals.pop(); n = vals.top();vals.pop(); if(s == ‘*‘) vals.push(n * m); else if(s == ‘+‘) vals.push(n + m); else if(s == ‘/‘) vals.push(n / m); else if(s == ‘-‘) vals.push(n - m); if((op2 == ‘)‘ && ops.top() == ‘(‘) || (op2 == ‘#‘ && ops.top() == ‘#‘)) ops.pop(); else ops.push(op2); } } int main(){ //freopen("in.txt","r",stdin); char x; ops.push(‘#‘); while((x = getchar()) != EOF){ //cout<<x; if(((x > ‘9‘)||(x < ‘0‘)) && !mid.empty()) { vals.push(mid.top()); while(!mid.empty()) mid.pop(); } else if(x >= ‘0‘ && x <= ‘9‘) { if(mid.empty()) {n = x - ‘0‘;mid.push(n);} else if(!mid.empty()){ m = mid.top(); n = m*10 + x - ‘0‘; mid.pop(); mid.push(n); } } if(x == ‘\n‘) { ops.push(‘#‘); while (!ops.empty()){ char s = ops.top();ops.pop(); cal_operator(s); } break; } if(x > ‘9‘ || x < ‘0‘) cal_operator(x); } return 0; }
以上是关于栈的应用:表达式求值运算的主要内容,如果未能解决你的问题,请参考以下文章