完成bool In(char ch); char Precede(char theta1, char theta2); char Operate(char first, char theta, char second);三个函数,使算法实现正确的表达式求值功能。
【样例输入】
3*(7-2)#
【样例输出】
15
#include
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
typedef char ElemType;
typedef int Status;
const char oper[7] = { '+', '-', '*', '/', '(', ')', '#' };
//顺序栈结构体声明
typedef struct SqStack{
ElemType *base;
int stacksize; //栈可用的最大空间
ElemType *top;
}SqStack;
/*基本操作声明部分*/
Status InitStack(SqStack &S); //顺序栈初始化
Status Push(SqStack &S, ElemType e); //进栈
Status Pop(SqStack &S, ElemType &e); //出栈
ElemType GetTop(SqStack S); //取栈顶元素
bool In(char ch) {
//请完成判断ch是否为运算符
}//In
/*判定栈顶元素与读入运算符之间优先关系*/
char Precede(char theta1, char theta2) {
//请完成判断运算符优先级
}//Precede
char Operate(char first, char theta, char second) {
//请完成计算两数运算结果
}//Operate
/*求值函数*/
ElemType EvaluateExpression( ) {
SqStack OPTR,OPND;
char ch,theta,a,b,x;
InitStack (OPTR);
Push (OPTR,'#') ;
InitStack (OPND);
cin>>ch;
while(ch!= '#' || GetTop(OPTR)!='#') {
if (! In(ch)){
Push(OPND,ch);
cin>>ch;
} // ch不是运算符则进栈
else
switch (Precede(GetTop(OPTR),ch)) { //比较优先权
case '<' : //当前字符ch压入OPTR栈,读入下一字符ch
Push(OPTR, ch);
cin>>ch;
break;
case '>' : //弹出OPTR栈顶的运算符运算,并将运算结果入栈
Pop(OPTR, theta);
Pop(OPND, b);
Pop(OPND, a);
Push(OPND, Operate(a, theta, b));
break;
case '=' : //脱括号并接收下一字符
Pop(OPTR,x);
cin>>ch;
break;
} // switch
} // while
return GetTop(OPND);} // EvaluateExpression
int main(){
ElemType result=EvaluateExpression();
cout<48<0;
}
Status InitStack(SqStack &S){
S.base=new ElemType[MAXSIZE];
if(!S.base) return OVERFLOW;
S.stacksize=MAXSIZE;
S.top=S.base;
return OK;
}
Status Push(SqStack &S, ElemType e){
if(S.top-S.base==S.stacksize) return ERROR;
*S.top=e;
S.top++; //*S.top++=e;
return OK;
}
Status Pop(SqStack &S, ElemType &e){
if(S.top==S.base) return ERROR;
S.top--; //S.top=S.top-1;
e=*S.top; //e=*--S.top;
return OK;
}
ElemType GetTop(SqStack S){
ElemType e;
if(S.top==S.base) return ERROR;
e=*(S.top-1);
return e;
}