算法表达式求值
摘要:
两个栈:操作数栈OPND,操作符号栈OPTR
在表达式后加#
符号栈初始化时#入栈
每读一个字符:
当它是#并且符号栈栈顶也是#时结束算法
当它是操作数时,进数栈
当它是符号时:
1.如果符号栈顶的优先级小于它,进符号栈
2.如果符号栈顶的优先级大于它,出两个数,出一个符号,计算后入数栈
3.如果与符号栈顶优先级相等,那说明是栈顶为(,它是),(出栈
// ExpressValue.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <stack> #include <map> using namespace std; int operate(int p,char opera,int q) { switch(opera) { case '+': return q+p; case '-': return p-q; case '*': return p*q; case '/': return p/q; } throw "no this operation:" + opera; } bool in(char c,char array[]){ int length = strlen(array); for(int i=0;i<length;i++) if(c==array[i])return true; return false; } typedef map<char,int> MAP; MAP opt; char t[][7]={ {'>','>','<','<','<','>','>'}, {'>','>','<','<','<','>','>'}, {'>','>','>','>','<','>','>'}, {'>','>','>','>','<','>','>'}, {'<','<','<','<','<','=',0}, {'>','>','>','>',0,'>','>'}, {'<','<','<','<','<',0,'='} }; char precede(char a,char b){ return t[opt[a]][opt[b]]; } int main(int argc, char* argv[]) { freopen("i://t.txt","r",stdin); char op[]={'+','-','*','/','(',')','#',0}; opt.insert(MAP::value_type('+',0)); opt.insert(MAP::value_type('-',1)); opt.insert(MAP::value_type('*',2)); opt.insert(MAP::value_type('/',3)); opt.insert(MAP::value_type('(',4)); opt.insert(MAP::value_type(')',5)); opt.insert(MAP::value_type('#',6)); while(1){ stack<char> optr,opnd; optr.push('#'); char c = getchar(); if(c=='e')return 0; while(!(c=='#'&&optr.top()=='#')){ if(!in(c,op)){ opnd.push(c-'0'); c = getchar(); } else{ switch(precede(optr.top(),c)){ case '<': optr.push(c); c = getchar(); break; case '=': optr.pop(); c = getchar(); break; case '>': int a = opnd.top(); opnd.pop(); int b = opnd.top(); opnd.pop(); char ope = optr.top(); optr.pop(); opnd.push(operate(b,ope,a)); //printf("[%d %c %d = %d]",b,ope,a,operate(b,ope,a)); break; } } } printf("%d\n",opnd.top()); } return 0; }
测试数据:
1+1+2# 2*3+5# 1# 4/2+6# 6*2*(2+5)# 6*2*(2+5)/7# 1+8/(1+1)# 2*(4+4)/8+8-2# 8*9/3-8# end
躲猫猫社团团长 http://t.sina.com.cn/coolria