//注意易错点pop函数的参数
#include<bits/stdc++.h>
using namespace std;
#define MAXSIZE 100
#define OK 1
#define OVERFLOW -1
#define ERROR 0
typedef char SElemType;
typedef int NElemType;
typedef int Status;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
typedef struct{
NElemType *base;
NElemType *top;
int stacksize;
}NqStack;
char sign[7]={'+','-','*','/','(',')','#'};
string relat[7]={
">><<<>>",
">><<<>>",
">>>><>>",
">>>><>>",
"<<<<<=0",
">>>>0>>",
"<<<<<0="
};
Status InitStackS(SqStack &S){
S.base=new SElemType(MAXSIZE);
if(!S.base) exit(OVERFLOW);
S.top=S.base;
S.stacksize=MAXSIZE;
return OK;
}
Status InitStackN(NqStack &S){
S.base=new NElemType(MAXSIZE);
if(!S.base) exit(OVERFLOW);
S.top=S.base;
S.stacksize=MAXSIZE;
return OK;
}
Status PushS(SqStack &S,SElemType ch){
if(S.top-S.base==S.stacksize){
return ERROR;
}
*S.top=ch;
S.top++;
return OK;
}
Status PushN(NqStack &S,NElemType ch){
if(S.top-S.base==S.stacksize){
return ERROR;
}
*S.top=ch;
S.top++;
return OK;
}
SElemType Gettop(SqStack S){
if(S.top!=S.base){
return *(S.top-1);
}
}
NElemType Gettop(NqStack S){
if(S.top!=S.base){
return *(S.top-1);
}
}
SElemType compare(SElemType a,SElemType b){
int id1=-1,id2=-1;
for(int i=0;i<7;i++){
if(sign[i]==a){
id1=i;
}
if(sign[i]==b){
id2=i;
}
}
if(id1==-1) return '-1';
return relat[id1][id2];
}
Status PopS(SqStack &S,SElemType &e){//易错点:Pop函数的第二个参数e前面需要加个&,因为e的值会改变
if(S.top==S.base){
return ERROR;
}
S.top--;
e=*S.top;
return OK;
}
Status PopN(NqStack &S,NElemType &e){
if(S.top==S.base){
return ERROR;
}
S.top--;
e=*S.top;
return OK;
}
NElemType Operate(NElemType a,SElemType theta,NElemType b){
switch(theta){
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
}
}
NElemType EvaluateExpression(){
SqStack OPTR;
NqStack OPND;
InitStackN(OPND);
InitStackS(OPTR);
PushS(OPTR,'#');
char ch,theta,x;
int a,b;
cin>>ch;
while(ch!='#' || Gettop(OPTR)!='#'){
switch(compare(Gettop(OPTR),ch)){
case '<':
PushS(OPTR,ch);
cin>>ch;
break;
case '>':
PopS(OPTR,theta);
PopN(OPND,b);
PopN(OPND,a);
PushN(OPND,Operate(a,theta,b));
break;
case '=':
PopS(OPTR,x);
cin>>ch;
break;
default:
int n=ch-'0';
cin>>ch;
while(ch>='0'&&ch<='9')
{
n = n*10+ch-'0';
cin>>ch;
}
PushN(OPND,n);
}
}
return Gettop(OPND);
}
int main(){
cout<<"请输入算术表达式,并以#结尾\n";
cout<<EvaluateExpression();
}
表达式求值(栈)
最新推荐文章于 2024-05-20 20:08:58 发布