标签:
将中缀表达式转成后缀表达式。
#include<iostream> #include <stack> #include<map> #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> using namespace std; //把中缀表达式转化为后缀表达式 a+b-a*((c+d)/e-f)+g# 1+2-3*((4+5)/3-6)+7#e int Complete(int a,int b,char c){ if(c==‘+‘){ return a+b; }else if(c==‘-‘){ return a-b; }else if(c==‘*‘){ return a*b; }else return a/b; } //void InitS() int main(){ map<char,int> ispM; map<char,int> icpM; stack<int> s1; stack<char> s2; char res[20]; ispM[‘#‘]=0;ispM[‘(‘]=1;ispM[‘*‘]=ispM[‘/‘]=5;ispM[‘+‘]=ispM[‘-‘]=3;ispM[‘)‘]=6; icpM[‘#‘]=0;icpM[‘(‘]=6;icpM[‘*‘]=icpM[‘/‘]=4;icpM[‘+‘]=icpM[‘-‘]=2;icpM[‘)‘]=1; s2.push(‘#‘); char c; //InitS(); int coun=0; memset(res,0,sizeof(res)); while(scanf("%c",&c)!=EOF){ if(c==‘e‘) { break; } if(c>=‘0‘&&c<=‘9‘){ res[coun++]=c; // cout<<c; }else{ if(ispM[s2.top()]>icpM[c]){ while(ispM[s2.top()]>icpM[c]){ res[coun++]=s2.top(); s2.pop(); } } if(ispM[s2.top()]<icpM[c]){ s2.push(c); } if(ispM[s2.top()]==icpM[c]){ s2.pop(); } } } for(int i=0;i<coun;i++){ if(res[i]>=‘0‘&&res[i]<=‘9‘){ s1.push(res[i]-‘0‘); }else { int t1=s1.top(); s1.pop(); int t2=s1.top(); s1.pop(); int newdata=Complete(t2,t1,res[i]); s1.push(newdata); } } cout<<s1.top()<<endl; s1.pop(); return 0; }
标签:
原文地址:http://www.cnblogs.com/wintersong/p/5727103.html