其中只有“(”,“)”,“0-9”,“+”,“-”,“*”,“/”,“^”
我的代码
#include<bits/stdc++.h>
using namespace std;
long long a[1000],top1,top2,ans,top3;
struct list{
char zf;
long long num;
}z3[11451];
bool zfpd(int x)
{
if(x<'1'||x>'9')
return 1;
else
return 0;
}
int main()
{
string z2,z1,s,c;
a['@']=-1;//初始化优先级
a['-']=1;
a['+']=1;
a['*']=3;
a['/']=2;
a['^']=4;
c.resize(40);//定义容量40
s.resize(40);
z1.resize(400);
z2.resize(400);
cin>>c;
for(int i=1;i<=c.size();i++)
s[i]=c[i-1];//将c赋值给s
s[0]='@';
z2[0]='@';
for(int i=0;i<=s.size()-1;i++)//运行s.size()次,模拟入栈
{
top1++;
z1[top1]=s[i];//z1[top]赋值
if(z1[top1]=='(')//判断z[1]top1为左右括号的情况
{
top1--;//是左括号盏一就将其出盏
top2++;//
z2[top2]='(';
continue;
}
if(z1[top1]==')')//如上
{
top1--;
while(z2[top2]!='(')//当z2[top2]不为'('就一直弹出
{
top1++;
z1[top1]=z2[top2];//
top2--;
}
top2--;
continue;
}
if(z1[top1]<'1'||z1[top1]>'9')
{
top2++;
z2[top2]=z1[top1];
top1--;
while(a[z2[top2]]<a[z2[top2-1]]&&zfpd(z2[top2-1]))
{
top1++;
z1[top1]=z2[top2-1];
z2[top2-1]=z2[top2];
top2--;
}
}
}
/////////////////////上面为转后缀表达式下面为后缀表达式计算
for(int i=1;i<=top1;i++)
{
top3++;
if(zfpd(z1[top1])){
z3[top3].zf=z1[top1];
}
if(!zfpd(z1[top1])){
z3[top3].num=int(z1[top1]);
}
if(zfpd(z3[top3].zf))
{
if(z3[top3].zf=='+'){
z3[top3-2].num=z3[top3-1].num+z3[top3-2].num;
top3-=2;
}
if(z3[top3].zf=='-'){
z3[top3-2].num=z3[top3-2].num-z3[top3-1].num;
top3-=2;}
if(z3[top3].zf=='*'){
z3[top3-2].num=z3[top3-2].num*z3[top3-1].num;
top3-=2;}
if(z3[top3].zf=='/'&&z3[top3-1].num!=0){
z3[top3-2].num=z3[top3-2].num/z3[top3-1].num;
top3-=2;}
if(z3[top3].zf=='^'){
for(int i=1,o;i<=z3[top3-1].num-1;i++)
{
o=z3[top3-2].num;
z3[top3-2].num*=o;
}
top3-=2;
}
}
}
cout<<z3[top3].num;
return 0;
}