实验代码:
#include <stdio.h>
#include<stdlib.h>
#include <malloc.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAX_STACK 100
typedef int SElemType;
typedef int Status;
typedef struct{
SElemType base[MAX_STACK];
int top; //指示栈顶位置
}SqStack;
void InitStack(SqStack *S) {
S->top=-1;
}
void Push(SqStack *S,SElemType e){
if (S->top == MAX_STACK-1)
printf("\nStack is full");
else {
S->base[++S->top]=e;
}
}
void Pop(SqStack *S,SElemType *e){
if (S->top == MAX_STACK-1)
printf("\nStack is empty");
else {
*e=S->base[S->top--];
}
}
SElemType GetTop(SqStack S) {
if (S.top == -1)
printf("\nStack is empty");
else
return S.base[S.top];
}
void printStack(SqStack S){
printf("\n");
while(S.top!=-1){
printf("%d ",S.base[S.top--]);
}
}
int StackEmpty(SqStack S){
return S.top==-1?1:0;
}
int In(char c){
if(c>='0'&&c<='9')
return 0;
}
int comp[255][255];//存储了符号优先级的数组
int Precede(SElemType a,SElemType b){//判断谁的优先级高
return comp[a][b];
}
SElemType Operate(SElemType a,SElemType o,SElemType b){//对a b进行四则运算
SElemType answer;
switch(o){
case '+': answer=a+b-'0';break;
case '-': answer=a-b+'0';break;
case '*': answer=(a-'0')*(b-'0')+'0';break;
case '/': answer=(a-'0')/(b-'0')+'0';break;
}
return answer;
}
char EvaluateExpression() {//直接对表达式求值
SqStack OPND,OPTR;
SElemType c,x,theta; SElemType a,b;
InitStack(&OPTR); Push(&OPTR,'#');
InitStack(&OPND); c=getchar();
while(c!='#'||GetTop(OPTR)!='#') {
if (!In(c))
{ Push(&OPND,c);c=getchar(); }
else
switch (Precede(GetTop(OPTR),c)){
case -1: Push(&OPTR,c); c=getchar(); break;
case 0: Pop(&OPTR,&x); c=getchar();break;
case 1: Pop(&OPTR,&theta); Pop(&OPND,&b); Pop(&OPND,&a);
Push(&OPND,Operate(a,theta,b));
break;
}
}
c=GetTop(OPND);
return c;
}
int main(){
//-1 0 1 小 等 大
comp['+']['+']=1,comp['+']['-']=1,comp['+']['*']=-1,
comp['+']['/']=-1,comp['+']['(']=-1,comp['+'][')']=1,
comp['+']['#']=1,
comp['-']['+']=1,comp['-']['-']=1,comp['-']['*']=-1,
comp['-']['/']=-1,comp['-']['(']=-1,comp['-'][')']=1,
comp['-']['#']=1,
comp['*']['+']=1,comp['*']['-']=1,comp['*']['*']=1,
comp['*']['/']=1,comp['*']['(']=-1,comp['*'][')']=1,
comp['*']['#']=1,
comp['/']['+']=1,comp['/']['-']=1,comp['/']['*']=1,
comp['/']['/']=1,comp['/']['(']=-1,comp['/'][')']=1,
comp['/']['#']=1,
comp['(']['+']=-1,comp['(']['-']=-1,comp['(']['*']=-1,
comp['(']['/']=-1,comp['(']['(']=-1,comp['('][')']=0,
comp['(']['#']=99999,
comp[')']['+']=1,comp[')']['-']=1,comp[')']['*']=1,
comp[')']['/']=1,comp[')']['(']=99999,comp[')'][')']=1,
comp[')']['#']=1,
comp['#']['+']=-1,comp['#']['-']=-1,comp['#']['*']=-1,
comp['#']['/']=-1,comp['#']['(']=-1,comp['#'][')']=999,
comp['#']['#']=0;
SElemType answer=EvaluateExpression();
printf("\nanswerc = %c\n",answer);
return 0;
}
/*
样例输入:2*(3-2)-1*2/2+3#
*/
运行结果: