Think:
利用栈的性质, 将操作数进行储存即可
Problem Description
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
Input
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
Output
求该后缀式所对应的算术表达式的值,并输出之。
Example Input
59*684/-3*+#
Example Output
57
Hint
基本操作数都是一位正整数!
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f
typedef int Elemtype;
typedef struct
{
Elemtype *elem;
int top;
int base;
} Stack;
void InitStack(Stack &S);
void Push(Stack &S, Elemtype key);
int main()
{
int i;
char str[10086];
while(cin >> str)
{
Stack S;
InitStack(S);
for (i = 0;str[i] != '#'; i ++)
{
if (str[i] == '+')
{
S.elem[S.top - 2] = S.elem[S.top - 2] + S.elem[S.top - 1];
S.top --;
}
else if (str[i] == '-')
{
S.elem[S.top - 2] = S.elem[S.top - 2] - S.elem[S.top - 1];
S.top --;
}
else if (str[i] == '*')
{
S.elem[S.top - 2] = S.elem[S.top - 2] * S.elem[S.top - 1];
S.top --;
}
else if (str[i] == '/')
{
S.elem[S.top - 2] = S.elem[S.top - 2] / S.elem[S.top - 1];
S.top --;
}
else
{
int key = str[i] - '0';
Push(S, key);
}
}
cout << S.elem[S.top - 1] << endl;
}
}
void InitStack(Stack &S)
{
S.elem = new int [INF];
S.top = S.base = 0;
}
void Push(Stack &S, Elemtype key)
{
S.elem[S.top] = key;
S.top ++;
}