Problem Description
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
Input
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
Output
求该后缀式所对应的算术表达式的值,并输出之。
Sample Input
59*684/-3*+#
Sample Output
57
Hint
基本操作数都是一位正整数!
题解:
后缀式求值就是在后缀式的基础上,如果是操作数就让它进栈,若果是运算符,就从栈顶取出两个操作数与运算符运算后再放到栈顶,直到计算到最后即可得出结果。
#include <stdio.h>
#include <stdlib.h>
#define stackinitsize 100
#define stackcreat 10
#define ok 1
#define overflow -1
#define error -1
typedef int elemtype;
typedef struct
{
elemtype *base;
elemtype *top;
int stacksize;
} sqstack;
int initstack(sqstack *s)
{
s->base=(elemtype*)malloc(stackinitsize*sizeof(elemtype));
if(!s->base)exit(overflow);
s->top=s->base;
s->stacksize=stackinitsize;
return ok;
}
int push(sqstack *s,elemtype e)
{
if(s->top-s->base>=s->stacksize)
{
s->top=(elemtype*)realloc(s->base,(s->stacksize+stackcreat)*sizeof(elemtype));
if(!s->base)exit(overflow);
s->top=s->base+s->stacksize;
}
*s->top++=e;
return ok;
}
int pop(sqstack *s)
{
if(s->top==s->base)return error;
s->top--;
return ok;
}
int stackempty(sqstack *s)
{
if(s->top==s->base)return 1;
else return 0;
}
int gettop(sqstack *s)
{
int e;
if(s->top==s->base)return error;
e=*(s->top-1);
return e;
}
int main()
{
char c;
int e,e1,e2;
sqstack s;
initstack(&s);
while(scanf("%c",&c)!=EOF)
{
if(c!='#')
{
if(c>='0'&&c<='9')
{
c=c-'0';
push(&s,c);
}
else if(c=='+'||c=='-'||c=='*'||c=='/')
{
e1=gettop(&s);
pop(&s);
e2=gettop(&s);
pop(&s);
if(c=='+')e=e1+e2;
if(c=='-')e=e2-e1;
if(c=='*')e=e2*e1;
if(c=='/')e=e2/e1;
push(&s,e);
}
}
if(c=='#')
{
e=gettop(&s);
printf("%d\n",e);
break;
}
}
return 0;
}