int OperatorPri(char opt)
{
switch(opt)
{
case '#':return 0;
case ')':return 1;
case '+':
case '-':return 2;
case '*':
case '/':return 3;
case '(':return 4;
default:return -1;
}
}
int PreOrder(char opt1,char opt2)
{
int i=OperatorPri(opt1);
int j=OperatorPri(opt2);
if(opt2=='(')return 1;
if(i==-1||j==-1)return -1;
if(i>j){return 1;}
else if(i==j){return 0;}
else { return -1;}
}
bool isOpr(char *p)
{
if(*p>='0' && *p<='9')return true;
else return false;
}
char *getNum(char *p,int &num)
{
num = 0;
while(isOpr(p)){num=10*num+(*p-'0');p++;}
p--;
return p;
}
int express(int e1,int e2,char opt)
{
cout<<e1<<opt<<e2<<" is calculated!"<<endl;
switch(opt){
case '+':
return e1+e2;
case '-':
return e1-e2;
case '*':
return e1*e2;
case '/':
return e1/e2;
default:syserr("not a opt");
}
}
int Calc(char *s)
{
bool flag=false;
MyStack<char> opt;
char c;
MyStack<int> opr;
int e1,e2,e;
opt.init();
opr.init();
opt.push('#');
char *p = s;
while(*p!='#')
{
if(isOpr(p)){
p=getNum(p,e);
opr.push(e);
}else{
opt.getTop(c);
if(PreOrder(*p,c) > 0){
opt.push(*p);
cout<<*p<<" is pushed"<<endl;
}else{
opt.pop(c);
cout<<c<<" is poped"<<endl;
opr.pop(e1);
opr.pop(e2);
opr.push(express(e2,e1,c));cout<<express(e2,e1,c)<<" pushed"<<endl;
if(*p=='+'||*p=='-'||*p=='*'||*p=='/'){opt.push(*p);cout<<*p<<" is pushed"<<endl;}
if(*p==')')
{
opt.getTop(c);
if(c!='('){
opt.pop(c);cout<<c<<" is poped"<<endl;
opr.pop(e1);opr.pop(e2);
opr.push(express(e2,e1,c));
cout<<express(e2,e1,c)<<" pushed"<<endl;
opt.pop(c);cout<<c<<" is poped"<<endl;
}
else{opt.pop(c);cout<<c<<" is poped"<<endl;}
}
}
}
p++;
}
if(*p=='#')
{
opt.pop(c);
cout<<c<<" is poped"<<endl;
opr.pop(e1);
opr.pop(e2);
opr.push(express(e2,e1,c));cout<<express(e2,e1,c)<<" pushed"<<endl;
opt.getTop(c);
if(c!='#'){
cout<<"YYYYYYYYYYY"<<endl;
opt.pop(c);cout<<c<<" is poped"<<endl;
opr.pop(e1);opr.pop(e2);
opr.push(express(e2,e1,c));
cout<<express(e2,e1,c)<<" pushed"<<endl;
opt.pop(c);cout<<c<<" is poped"<<endl;
}
else{opt.pop(c);cout<<c<<" is poped"<<endl;}
}
opr.pop(e);
cout<<"e is "<<e<<endl;
opt.print();opr.print();
if(opt.isEmpty() && opr.isEmpty()){flag = true;}
opt.destroy();
opr.destroy();
if(flag) return e;
else return -1;
}
栈的应用:计算器的实现
最新推荐文章于 2024-04-27 23:54:07 发布