[UPC] Postfix Evaluation 后缀表达式求值 | 栈的简单应用

题目描述

In a postfix expression, operators follow their operands. For example, [ 5 2 * ] is interpreted as 5 * 2. If there are multiple operators, each operator appears after its last operand. Here are more examples, showing how postfix compares to parenthesized expressions:
6   3 + 5 ∗ 2 − 6 3 + 5 * 2 − 6 3+52 等同 ( ( 6 + 3 ) ∗ 5 ) – 2 ) ((6 + 3) * 5) – 2) ((6+3)5)2)

4   3   2 ∗ + 4 3 2 * + 4 3 2+ 等同 4 + ( 3 ∗ 2 ) 4 + (3 * 2) 4+(32)
These examples show that the operand affected by an operator can be the result of a previous calculation.
Here is what you need to do: Given an integer postfix expression, you must calculate and print its value.

输入

Each input will consist of a single test case. Your program will be run multiple times on different inputs.
A single input line will contain a postfix expression containing single digit integers and operators from the following set: { +, –, /, * } (add, subtract, divide, multiply). There will be a single space between each digit and and operator. The line will contain no more than 64 operators and numbers, total.

输出

Output will be a single integer on a line by itself.
样例输入 Copy

【样例16 3 + 5 * 2 –
【样例26 3 + 5 2 * *
【样例34 3 2 * + 

样例输出 Copy

【样例143
【样例290
【样例310
stack<ll> st;
int main() {
	char c;
	while(cin >> c) {
		if(isdigit(c)){
			st.push(c - '0');
		}else{
			ll a = st.top();
			st.pop();
			ll b = st.top();
			st.pop();
			if(c == '+') st.push(a + b);
			else if(c == '-') st.push(b - a);
			else if(c == '*') st.push(a * b);
			else st.push(b / a);
		}
	}
	cout << st.top() << endl;
	return 0;
}
/**


**/

原文地址:https://www.cnblogs.com/PushyTao/p/15459789.html