#include <errno.h>
#include<list>
#include<algorithm>
#include<cstdio>
#include<vector>
#include <iostream>
#include<string>
#include<stack>
#define INT_MAX (1<<30)
using namespace std;
int get(char ch){
switch(ch){
case '+':
case '-':return 1;
case '*':
case '/':return 2;
default:return 0;
}
}
bool isLower(char s1,char s2){
return get(s1)<get(s2);
}
void change(const string& s,string & res){
stack<char> s1,s2;
s1.push('#');
int i=0;
while(i<s.length()){
if(s[i]=='('){
s1.push(s[i]);i++;
}else if(s[i]==')'){
while(s1.top()!='('){
res+=s1.top();
res+=' ';
s1.pop();
}
s1.pop();
i++;
}else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){
while(get(s1.top())>=get(s[i])){
res+=s1.top();s1.pop();
res+=' ';
}
s1.push(s[i]);
i++;
}else{
while(isdigit(s[i])||s[i]=='.'){
res+=s[i];i++;
}
res+=' ';
}
}
while(s1.top()!='#'){
res+=s1.top();s1.pop();
res+=' ';
}
}
double value(string s2){
stack<double> s;
double x,y;
int i=0;
while(i<s2.length()){
if(s2[i]==' ') {i++;continue;}
switch(s2[i]){
case '+':x=s.top();s.pop();x+=s.top();s.pop();++i;break;
case '-':x=s.top();s.pop();x=s.top()-x;s.pop();++i;break;
case '*':x=s.top();s.pop();x*=s.top();s.pop();++i;break;
case '/':x=s.top();s.pop();x=s.top()/x;s.pop();++i;break;
default:
{
x=0;
while(isdigit(s2[i])){
x=x*10+s2[i]-'0';
i++;
}
if(s2[i]=='.'){
double k=10.0;
y=0;
i++;
while(isdigit(s2[i])){
y+=((s2[i]-'0')/k);
i++;
k*=10;
}
x+=y;
}
}
}
s.push(x);
}
return s.top();
}
int main(){
string res;
change("3-2+25*2",res);
cout<<value(res)<<endl;
return 0;
}
只考虑加减乘除的版本,从中缀表达式转到后缀表达式:
void change(const string& s,string & res){
stack<char> sta;
int i=0;
while(i<s.length()){
if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){
while(!sta.empty()&&get(sta.top())>=get(s[i])){
res+=sta.top();
res+=' ';
sta.pop();
}
sta.push(s[i]);
i++;
}else{
while(isdigit(s[i])){
res+=s[i];
i++;
}
res+=' ';
}
}
while(!sta.empty()){
res+=sta.top();
res+=' ';
sta.pop();
}
}