求中缀表达式的值
分享一道经典的栈与队列题目。
#include <iostream>
#include <string>
#include <cstring>
#include <queue>
#include <stack>
using namespace std;
const int N = 605;
struct node{
int x;
char y;
node(int a=0,char b=0):x(a),y(b){}
};
queue<node> q;
stack<char> s;
stack<int> p;
bool isoperator(char a){
if(a=='+' || a=='-' || a=='*' || a=='/')
return true;
return false;
}
bool isnum(char a){
if(a >= '0' && a<= '9')
return true;
return false;
}
bool isgreater(char a, char b){
if((a=='*' || a=='/') && (b=='+' || b=='-'))
return true;
return false;
}
void init(){
while(!q.empty()) q.pop();
while(!s.empty()) s.pop();
while(!p.empty()) p.pop();
}
int main(){
int n;
cin >> n;
while(n--){
init();
char a[N];
cin >> a;
for(int i=0;a[i];++i){
if(a[i] == '('){
s.push(a[i]);
}
else if(a[i] == ')'){
while(!s.empty()){
char c = s.top();
s.pop();
if(c == '(') break;
else q.push(node(0,c));
}
}
else if(isoperator(a[i])){
while(!s.empty()&&s.top()!='('&&!isgreater(a[i],s.top())){
char c = s.top();
s.pop();
q.push(node(0,c));
}
s.push(a[i]);
}
else if(isnum(a[i])){
int t = atoi(a+i);
while(a[i] && isnum(a[i])){ // in case the end
i++;
}
i--;
q.push(node(t));
}
}
while(!s.empty()){
q.push(node(0,s.top()));
s.pop();
}
while(!q.empty()){
node t = q.front();
q.pop();
if(t.y){
int t2 = p.top();p.pop();
int t1 = p.top();p.pop();
int tmp=0;
switch (t.y) {
case '+':tmp=t1+t2;break;
case '-':tmp=t1-t2;break;
case '*':tmp=t1*t2;break;
case '/':tmp=t1/t2;break;
default : break;
}
p.push(tmp);
}
else{
p.push(t.x);
}
}
cout << p.top() << endl;
}
return 0;
}