利用栈表达式求值
头文件:
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}Sqstack;
Status Initstack(Sqstack &S)
{
S.base=new SElemType[MAXSIZE];
if(!S.base) exit(OVERFLOW);
S.top=S.base;
S.stacksize=MAXSIZE;
return OK;
}
Status emptystack(Sqstack S)
{
if(S.top==S.base)
return 1;
else return 0;
}
Status push(Sqstack &S,SElemType e)
{
if(S.top-S.base==S.stacksize) return ERROR;
*S.top++=e;
return OK;
}
Status Pop(Sqstack &S,SElemType &e)
{
if(S.top==S.base)
return ERROR;
e=*--S.top;
return OK;
}
Status GetTop(Sqstack S)//),SElemType &e)
{
if(S.top!=S.base)
return *(S.top-1);
}
const char oper[7] = { '+', '-', '*', '/', '(', ')', '#' };
bool In(char ch) {//判断ch是否为运算符
int i;
for ( i = 0; i < 7; i++) {
if (ch == oper[i]) {
return true;
}
}
return false;
}
char Precede(char theta1, char theta2) {//判断运算符优先级
if ((theta1 == '(' && theta2 == ')') || (theta1 == '#' && theta2 == '#')) {
return '=';
} else if (theta1 == '(' || theta1 == '#' || theta2 == '(' || (theta1
== '+' || theta1 == '-') && (theta2 == '*' || theta2 == '/')) {
return '<';
} else
return '>';
}
char Operate(char first, char theta, char second) {//计算两数运算结果
switch (theta) {
case '+':
return (first - '0') + (second - '0') + 48;
case '-':
return (first - '0') - (second - '0') + 48;
case '*':
return (first - '0') * (second - '0') + 48;
case '/':
return (first - '0') / (second - '0') + 48;
}
return 0;
}
主函数
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
typedef int DataType;
typedef int Status;
typedef int SElemType;
#include"Sqstack.h"
int PostExp(char str[]){
DataType x,x1,x2;
int i;
Sqstack OPND;
Initstack(OPND);
for(i=0;str[i]!='#';i++)
{
if(isdigit(str[i])) //isdigit函数判断数组中的字符是否为数字
{
x=(int)(str[i]-48);
push(OPND,x);
}
else
{
Pop(OPND,x2);
Pop(OPND,x1);
switch(str[i])
{
case '+':{x1+=x2;break;}
case '-':{x1-=x2;break;}
case '*':{x1*=x2;break;}
case '/':
if(x2==0.0){printf("除数为零\n"); exit(0);}
else{x1/=x2;break;}
}
push(OPND,x1);
}
}
Pop(OPND,x1);
return x1;
}
int main()
{
char str[]="123+4*5-+#";
PostExp(str);
printf("结果为:%d",PostExp(str));
return 0;
}
补充:后缀到中缀表达式*#的转换
例:63/5+6#*
首先从左往右扫描先碰到/号,取/号前面两个操作数:6,3 得到:6/3;
继续往下扫碰到+号,取5和6/3得到:6/3+5;
继续向后扫描碰到+号,取(6/3+5)和6得到:(6/3+5)6;
后缀63/5+6与中缀的比较(6/3+5)*6