数据结构实验之栈三:后缀式求值
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
Input
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
Output
求该后缀式所对应的算术表达式的值,并输出之。
Example Input
59*684/-3*+#
Example Output
57
Hint
基本操作数都是一位正整数!
#include <stdio.h>
#include <stdlib.h>
int a[2000];//数组模拟栈
int top;
int main()
{
char c;
int x, y;
top = -1;
c = getchar();
while(c != '#')
{
if(c >= '0' && c <= '9')//遇到数字直接进栈
{
a[++top] = c - '0';
}
else//遇到运算符
{
x = a[top--];//顶出两个数
y = a[top--];
if(c == '*'){//对他们进行运算,再将其,压入栈
a[++top] = x * y;
}
else if(c == '/'){
a[++top] = y / x;
}
else if(c == '+'){
a[++top] = y + x;
}
else if(c == '-'){
a[++top] = y - x;
}
}
c = getchar();
}
printf("%d\n", a[top]);//输出结果就好
return 0;
}