今天上数据结构,王老师讲的用栈实现算术表达式的值,晚上在实验室写了下,感觉自己的代码还是有问题(虽然还自己没有找到),感觉这个代码关于括号内运算符的优先级关系还是没有考虑好,这个代码也只是局限在10以内的加减乘除;先贴下代码,以后再来优化:
#include <iostream>
#include <stack>#include <cstring>#include <cstdio>using namespace std;stack<int> s2;stack<int> s1;char sign[4]={'+','-','*','/'};char exp[110];bool flag;int cal(int a,int b,int c){ if(c==0) return a+b; if(c==1) return a-b; if(c==2) return a*b; if(c==3) return a/b;}int solve(){ flag=0; int len=strlen(exp); exp[len]='#'; len++; while(!s2.empty()) s2.pop(); //s1.push(-1); int c=-1; for(int i=0;i<len;i++) { // cout<<exp[i]<<" "; if(s1.size()==0&&s2.size()==1&&i==len-1) { return s2.top(); } if(exp[i]>='0'&&exp[i]<='9') { s2.push(exp[i]-'0'); } else if(exp[i]=='(') { s1.push(4); flag=1; } else if(exp[i]==')'&&(c=s1.top())!=4) { s1.pop(); int t1=s2.top(); s2.pop(); int t2=s2.top(); s2.pop(); int temp=cal(t2,t1,c); // cout<<temp<<"fgf "; s2.push(temp); i--; } else if(exp[i]==')'&&(c=s1.top())==4) { s1.pop(); flag=0; } else { int j; if(!s1.empty()) c=s1.top(); else c=-1; for(j=0;j<4;j++) if(exp[i]==sign[j]) break; // cout<<j<<" "<<exp[i]<<endl; if(flag&&j+5>c&&j<4) { s1.push(j); // cout<<c<<" "<<j<<" df "<<exp[i]<<endl; } else if(!flag&&j>c&&j<4) s1.push(j); else { s1.pop(); int t1=s2.top(); s2.pop(); int t2=s2.top(); s2.pop(); int temp=cal(t2,t1,c); s2.push(temp); //cout<<temp<<" fg "; i--; } } } return -1;}int main(){ while(scanf("%s",exp)) { cout<<solve()<<endl; } return 0;}