表达式求值(栈)

//注意易错点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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值