数据结构是一门伟大的学科,希望诸君认真对待。此代码已在C-free编译器上验证通过,支持多重括号。
#include<iostream>
using namespace std;
#include<cmath>
struct optrstack//运算符建栈
{
char *optrbase;
char *optrtop;
};
void optrinit(optrstack *st)//运算符初始化
{
st->optrbase=new char[100];
st->optrtop=st->optrbase;
}
void optrpush(optrstack *st,char e)//运算符入栈
{
*(st->optrtop++)=e;
}
void optrpop(optrstack *st,char &e)//运算符删除栈顶元素
{
e=*(--st->optrtop);
}
char optrgettop(optrstack *st)//运算符取栈顶元素
{
return *(st->optrtop-1);
}
struct opndstack//操作数建栈
{
int *opndbase;
int *opndtop;
};
void opndinit(opndstack *st)//操作数初始化
{
st->opndbase=new int[100];
st->opndtop=st->opndbase;
}
void opndpush(opndstack *st,int e)//操作数入栈
{
*(st->opndtop++)=e;
}
void opndpop(opndstack *st,int &e)//操作数删除栈顶元素
{
e=*(--st->opndtop);
}
char precede(char a,char b)//各种运算符之间优先级判断
{
if(a=='+'||a=='-')
{
if(b=='*'||b=='/'||b=='(')
return '<';
else
return '>';
}
else if(a=='*'||a=='/')
{
if(b=='(')
return '<';
else
return '>';
}
else if(a=='(')
{
if(b==')')
return '=';
else
return '<';
}
else if(a==')')
{
return '>';
}
else if(a=='=')
{
if(b=='=')
return '=';
else
return '<';
}
else
cout<<"error"<<endl;
}
int f(char a[])//将数字字符串转化为int型
{
int i,x,j,k;
j=x=k=0;
for(i=0;a[i]!='/0';++i)
{
++j;
}
for(i=j-1;i>=0;--i)
{
x+=(a[i]-'0')*int(pow(10.0,k++));
}
return x;
}
int operate(int a,char theta,int b)//算术操作
{
switch(theta)
{
case'+':
return a+b;
break;
case'-':
return a-b;
break;
case'*':
return a*b;
break;
case'/':
return a/b;
break;
default:cout<<"error"<<endl;
}
}
int main()
{
int a,b;
char c[10],theta,x;
optrstack *optr=new optrstack;
opndstack *opnd=new opndstack;
optrinit(optr);
optrpush(optr,'=');
opndinit(opnd);
cin>>c;
while(c[0]!='='||optrgettop(optr)!='=')
{
if(c[0]>=48&&c[0]<=57)
{
opndpush(opnd,f(c));
cin>>c;
}
else
{
switch(precede(optrgettop(optr),c[0]))
{
case'<':
optrpush(optr,c[0]);
cin>>c;
break;
case'=':
optrpop(optr,x);
cin>>c;
break;
case'>':
optrpop(optr,theta);
opndpop(opnd,b);
opndpop(opnd,a);
opndpush(opnd,operate(a,theta,b));
break;
}
}
}
cout<<*opnd->opndbase<<endl;
return 0;
}