Problem Description
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
Input
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
Output
求该后缀式所对应的算术表达式的值,并输出之。
Example Input
59*684/-3*+#
Example Output
57
Hint
基本操作数都是一位正整数!
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#define STACKINITSIZE 100
#define STACKINCREMENT 10
#define OVERFLOW -2
#define ERROR -1
#define OK 1
typedef int SElemtype;
typedef int Statu;
typedef struct node
{
SElemtype *base;
SElemtype *top;
int stacksize;
}SqStack;
Statu Check(SqStack &S, char c);
Statu InitStack(SqStack &S);
Statu Push(SqStack &S, SElemtype e);
Statu Pop(SqStack &S, SElemtype &e);
int main()
{
char a;
SqStack S;
InitStack(S);
while(scanf("%c", &a) && a != '#')
{
Check(S, a);
}
printf("%d\n", *S.base);
return 0;
}
Statu InitStack(SqStack &S)
{
S.base = (SElemtype *)malloc(STACKINITSIZE * sizeof(SElemtype));
if(!S.base)
exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACKINITSIZE;
return OK;
}
Statu Push(SqStack &S, SElemtype e)
{
if(S.top - S.base >= S.stacksize)
{
S.base = (SElemtype *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemtype));
if(!S.base)
exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
* S.top++ = e;
return OK;
}
Statu Pop(SqStack &S, SElemtype &e)
{
if(S.top == S.base)
return ERROR;
e = * -- S.top;
return OK;
}
Statu Check(SqStack &S, char c)
{
int a, d;
switch(c)
{
case '+':Pop(S, a);Pop(S, d);Push(S, a + d);break;
case '-':Pop(S, a);Pop(S, d);Push(S, d - a);break;
case '*':Pop(S, a);Pop(S, d);Push(S, a * d);break;
case '/':Pop(S, a);Pop(S, d);Push(S, d / a);break;
default:Push(S, c - '0');
}
return OK;
}