数据结构实验之栈三:后缀式求值
Time Limit: 1000MS Memory limit: 65536K
题目描述
输入
输出
示例输入
59*684/-3*+#
示例输出
57
#include <stdio.h>
#include <stdlib.h>
#define stackmax 10000
#define stacknum 10000
typedef int ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
} SqStack;
int InitStack(SqStack &s)
{
s.base = (ElemType*) malloc (stackmax*sizeof(ElemType));
if (! s.base)
exit(0);
s.top = s.base;
s.stacksize = stackmax;
return 0;
}
int Push(SqStack &s , int e)
{
if(s.top-s.base >= s.stacksize)
{
s.base = (ElemType *)realloc(s.base,(s.stacksize+stacknum)*sizeof(ElemType));
if (! s.base ) exit(0);
s.top = s.base + s.stacksize;
s.stacksize += stacknum;
}
*s.top++=e;
}
void putstack(SqStack &s)
{
while(s.top > s.base)
{
printf("%d", *(s.top-1));
s.top--;
}
printf("\n");
}
int Pop(SqStack &s)
{
if(s.top == s.base) return 0;
s.top--;
return 1;
}
int GetTop(SqStack &s)
{
if(s.top == s.base) return 0;
int e=*(s.top-1);
return e;
}
int operate(int a, char theta, int b)
{
int e;
if(theta=='+')
e=a+b;
if(theta=='-')
e=b-a;
if(theta=='*')
e=b*a;
if(theta=='/')
e=b/a;
return e;
}//注意b与a的运算次序
int evaluation(SqStack &s, char c)
{
int a, b;
if(c>='0'&&c<='9')
{
Push(s, c-'0');
}
else
{
a=GetTop(s);
Pop(s);
b=GetTop(s);
Pop(s);
Push(s, operate(a, c, b));
}
}
int main()
{
char c;
SqStack s;
InitStack(s);
while(~scanf("%c", &c)&&c!='#')
{
evaluation(s, c);
}
printf("%d", *s.base);
}