先中缀转后缀,再用stack求后缀,这个只支持二元运算符
#include<iostream>
#include<string>
#include<stack>
#include<vector>
using namespace std;
long long get_val(string str){
long long out = 0;
for(int i=0; i<str.size(); ++i){
out *= 10;
out += str[i]-'0';
}
return out;
}
string get_str(long long num){
string out = "";
if(num == 0)
out = "0";
else{
while(num){
string temp(1, '0' + num%10);
out = out + temp;
num /= 10;
}
}
return out;
}
int rank(char ch){
if(ch == '+' || ch == '-')
return 1;
else
return 2;
}
vector<string> middle2post(string str){
stack<char> exp;
vector<string> post;
for(int i=0; i<str.size(); ++i){
if(str[i] >= '0' && str[i] <= '9'){
string temp(1, str[i]);
while(i+1 < str.size() && str[i+1] >= '0' && str[i+1] <= '9'){
temp.push_back(str[i+1]);
++i;
}
post.push_back(temp);
cout << temp;
}
else if(str[i] == '(')
exp.push(str[i]);
else if(str[i] == ')'){
while(exp.top() != '('){
string temp(1, exp.top());
post.push_back(temp);
cout << temp;
exp.pop();
}
exp.pop();
}
else{
//cout << endl << "str: " << str[i] << endl;
if(exp.empty() || rank(str[i]) > rank(exp.top()))
exp.push(str[i]);
else{
while(!exp.empty() && exp.top() != '(' && rank(str[i]) <= rank(exp.top())){
string temp(1, exp.top());
post.push_back(temp);
cout << temp;
exp.pop();
}
exp.push(str[i]);
}
}
}
while(!exp.empty()){
string temp(1, exp.top());
post.push_back(temp);
cout << temp;
exp.pop();
}
cout << endl;
return post;
}
long long evaluate(vector<string> &vec){
stack<long long> temp;
for(int i=0; i<vec.size(); ++i){
if(vec[i][0] >= '0' && vec[i][0] <= '9')
temp.push(get_val(vec[i]));
else{
long long num1 = temp.top();
temp.pop();
long long num2 = temp.top();
temp.pop();
if(vec[i] == "+")
temp.push(num2 + num1);
if(vec[i] == "-")
temp.push(num2 - num1);
if(vec[i] == "*")
temp.push(num2 * num1);
if(vec[i] == "/")
temp.push(num2 / num1);
}
}
return temp.top();
}
int main(){
string str;
while(cin >> str){
vector<string> post = middle2post(str);
for(int i=0; i<post.size(); ++i)
cout << post[i] << " ";
cout << endl;
cout << evaluate(post) << endl;
}
return 0;
}