集训3-A题 栈用于后缀表达式

256 阅读1分钟

Yasaka with Postfix Expression Description

所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。

如:3×(5−2)+7对应的后缀表达式为:3.5.2.−7.+@。'@' 为表达式的结束符号。'.' 为操作数的结束符号。

Input

输入:后缀表达式

Output

输出:表达式的值

Sample Input 1

2.3.5.-7.*@

Sample Output 1

-14

#include <iostream>
#include <string>
#include <stack>
#include <stdio.h>
using namespace std;
int main()
{
    stack<int> sta;
    string s;
    cin >>s;
    int ans=0;
    for(int i=0;i<s.length();i++)
    {
        switch(s[i])
        {
            case '+':
            {
                int a=sta.top();
                sta.pop();
                int b=sta.top()+a;
                sta.pop();
                sta.push(b);
                break;
            }
            case '-':
            {
                int a=sta.top();
                sta.pop();
                int b=sta.top()-a;
                sta.pop();
                sta.push(b);
                break;
            }
            case '*':
            {
                int a=sta.top();
                sta.pop();
                int b=sta.top()*a;
                sta.pop();
                sta.push(b);
                break;
            }
            case '/':
            {
                int a=sta.top();
                sta.pop();
                int b=sta.top()/a;
                sta.pop();
                sta.push(b);
                break;
            }
            case '.':
            {
                sta.push(ans);
                ans=0;
                break;
            }
            case '@':
            {
                break;
            }
            default :
            {
                ans=ans*10+s[i]-48;//累加进位
                break;
            }
        }
    }
    printf("%d",sta.top());
    return 0;
}

此题用于对栈的理解,用于后缀表达式和前缀表达式的理解