代码如下:
#include<iostream>
#include<vector>
#include<stack>
class SimpleCal{
private:
std::stack<char> mOps;
std::stack<int> mDatas;
std::vector<char> mInfixVec;
std::vector<char> mPostfixVec;
public:
SimpleCal(std::vector<char> vec):mInfixVec(vec){
}
bool IsPriority(char op1,char op2){
return op1 != '+' && op1 != '-' && op2 != '*' && op2 != '/';
}
int CalTwoNum(char op,int a,int b){
switch (op)
{
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
}
return 0;
}
int CalInput(){
int res = 0;
InfixToPostfix();
for(auto i:mPostfixVec){
if(IsOper(i)){
int b = mDatas.top();
mDatas.pop();
int a = mDatas.top();
mDatas.pop();
int c = CalTwoNum(i,a,b);
mDatas.push(c);
}else{
mDatas.push(i-'0');
}
}
if(mDatas.empty()){
return res;
}else{
return mDatas.top();
}
}
void InfixToPostfix(){
for(auto i:mInfixVec){
if(!IsOper(i)){
mPostfixVec.push_back(i);
}else{
if(mOps.empty()){
mOps.push(i);
continue;
}else{
if(')' == i){
while('(' !=mOps.top()){
mPostfixVec.push_back(mOps.top());
mOps.pop();
}
if('(' ==mOps.top()){
mOps.pop();
}
}else if('(' == i){
mOps.push(i);
}else{
if(IsPriority(i,mOps.top())){
mOps.push(i);
}else{
while(!mOps.empty() && !IsPriority(i,mOps.top()) && mOps.top() != '('){
mPostfixVec.push_back(mOps.top());
mOps.pop();
}
mOps.push(i);
}
}
}
}
}
while(!mOps.empty()){
mPostfixVec.push_back(mOps.top());
mOps.pop();
}
}
bool IsOper(const char a){
if ('+' == a ||'-' == a||'*' == a||'/' == a||'(' == a||')' == a){
return true;
}
return false;
}
void PrintRes(){
int res = CalInput();
std::cout<<"中缀表达式:";
for(auto i :mInfixVec){
std::cout<<i;
}
std::cout<<std::endl;
std::cout<<"后缀表达式:";
for(auto i:mPostfixVec){
std::cout<<i;
}
std::cout<<std::endl;
std::cout<<"result:"<<res<<std::endl;
}
};
int main(){
// 1+2*4*(4+1)-5/2+3
SimpleCal cal(std::vector<char>{'1','+','2','*','4','*','(','4','+','1',')','-','5','/','2','+','3'});
// 1+2*4*((4+1)*3+1)-5/2+3
// SimpleCal cal(std::vector<char>{'1','+','2','*','4','*','(','(','4','+','1',')','*','3','+','1',')','-','5','/','2','+','3'});
// 2+9/3-5
// SimpleCal cal(std::vector<char>{'2','+','9','/','3','-','5'});
cal.PrintRes();
}