代码思路:参考数据结构(用面向对象方法与C++语言描述)
#include<bits/stdc++.h>
using namespace std;
class Transformation{
public:
Transformation(string expression){
this->expression=expression;
}
string transform(){
string xexpression="";
int len=1;
char stack[expression.length()];
stack[0]='#';
int i=0;
while(i<expression.length()){
if(!judge(expression[i])){
if(!judge(expression[i-1])){
xexpression+=expression[i];
}
else{
xexpression+=' ';
xexpression+=expression[i];
}
i++;
}
else{
if(icp(expression[i])>isp(stack[len-1])){
stack[len++]=expression[i];
i++;
}
else if(icp(expression[i])<isp(stack[len-1])){
xexpression+=' ';
xexpression+=stack[len-1];
len--;
}
else{
len--;
i++;
}
}
}
for(int i=len-1;i>0;i--){
xexpression+=' ';
xexpression+=stack[i];
}
return xexpression;
}
private:
string expression; //表达式
int isp(char c){ //栈内优先数
switch (c){
case '#':
return 0;
case '(':
return 1;
case '*':
case '/':
case '%':
return 5;
case '+':
case '-':
return 3;
case ')':
return 6;
default:
return -1;
}
}
int icp(char c){ //栈外优先数
switch (c){
case '#':
return 0;
case '(':
return 6;
case '*':
case '/':
case '%':
return 4;
case '+':
case '-':
return 2;
case ')':
return 1;
default:
return -1;
}
}
bool judge(char op){ //判断是否为操作符
if(op=='+'||op=='-'||op=='*'||op=='/'||op=='('||op==')'){
return true;
}
return false;
}
};
class Calculator{
public:
Calculator(string expression){
this->expression=expression;
}
int caculate(){
int stack[expression.length()];
int len=0;
int temp=-1;
for(int i=0;i<expression.length();i++){
if(judge(expression[i])){
int op2=stack[len-1];
int op1=stack[len-2];
len--;
stack[len-1]=operatorOperation(op1,op2,expression[i]);
}
else if(48<=expression[i] && expression[i]<=57){
if(temp!=-1){
temp=temp*10+(expression[i]-48);
}
else{
temp=(expression[i]-48);
}
}
else{
if(temp!=-1){
stack[len++]=temp;
}
temp=-1;
}
}
return stack[0];
}
private:
string expression;
bool judge(char op){ //判断是否为操作符
if(op=='+'||op=='-'||op=='*'||op=='/'||op=='('||op==')'){
return true;
}
return false;
}
int operatorOperation(int op1,int op2,char c){
switch (c)
{
case '+':
return op1+op2;
case '-':
return op1-op2;
case '*':
return op1*op2;
case '/':
return op1/op2;
default:
break;
}
}
};
int main(){
string s="1+2*(2-1)-2/2";
Transformation *tra=new Transformation(s);
cout<<tra->transform()<<endl;
Calculator *cal=new Calculator(tra->transform());
cout<<cal->caculate()<<endl;
delete tra;
system("pause");
return 0;
}