数据结构实验之栈三:后缀式求值
Time Limit: 1000MS Memory limit: 65536K
题目描述
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
输入
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
输出
求该后缀式所对应的算术表达式的值,并输出之。
示例输入
59*684/-3*+#
示例输出
57
提示
基本操作数都是一位正整数!
Time Limit: 1000MS Memory limit: 65536K
题目描述
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
输入
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
输出
求该后缀式所对应的算术表达式的值,并输出之。
示例输入
59*684/-3*+#
示例输出
57
提示
基本操作数都是一位正整数!
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# define STACK_INIT_SIZE 100
# define STACKINCREMENT 10
typedef int SelemType;
typedef struct{
SelemType *base;
SelemType *top;
int stacksize;
} SqStack;
void InitStack(SqStack&S);
void Push(SqStack&S,SelemType e);
void Pop(SqStack&S,SelemType&e);
/*栈空返回ture*/
bool StackEmpty(SqStack&S);
/*后缀表达式求值栈中存放的是数字,遇到运算符,栈若不空此时必有两个操作数,后缀式最后一个必为操作符
依次弹出两个数进行运算,将结果压入栈*/
int main()
{
int i=0;
char str[150];
int num1,num2,tmp,result;
SqStack S;
InitStack(S);
gets(str);
while(str[i]!='#')
{
if('0'<=str[i] && str[i]<='9')
{
tmp = str[i] - '0';
Push(S,tmp);
}
else /*if(!StackEmpty(S))*/
{
Pop(S,num2);
Pop(S,num1);
if(str[i] == '+')
{
tmp = num1 + num2;
Push(S,tmp);
}
if(str[i] == '-')
{
tmp = num1 - num2;
Push(S,tmp);
}
if(str[i] == '*')
{
tmp = num1 * num2;
Push(S,tmp);
}
if(str[i] == '/')
{
tmp = num1 / num2;
Push(S,tmp);
}
}
i++;
}
Pop(S,result);
printf("%d",result);
return 0;
}
void InitStack(SqStack&S)
{
S.base = (SelemType*)malloc(STACK_INIT_SIZE*sizeof(SelemType));
if(!S.base)
{
exit(0);
}
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
void Push(SqStack&S,SelemType e)
{
/*判断栈是否已满*/
if(S.top - S.base >= S.stacksize)
{
/*增大栈的规模*/
S.base = (SelemType*)realloc(S.base,(STACK_INIT_SIZE + STACKINCREMENT) * sizeof(SelemType));
if(!S.base)
{
exit(0);
}
/*重置S.top和S.stacksize*/
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
/*放入添加的元素*/
*S.top = e;
/*栈顶S.top上移*/
S.top++;
//*S.top++ = e;
}
void Pop(SqStack&S,SelemType&e)
{
/*判断栈是否为空,若为空直接返回*/
if(S.top == S.base)
return;
else
{
//e = *--S.top;
/*栈顶下移找到要Pop的元素*/
S.top--;
/*获取要出栈的元素*/
e = *S.top;
}
}
/*bool StackEmpty(SqStack&S)
{
if(S.top == S.base)
return true;
else
return false;
}
*/