Stack C++STL

还是C++的STL用起来最方便

可以通过这篇简单了解定义与几个操作如何用,然后就可以直接上手了
https://blog.csdn.net/lyj2014211626/article/details/66967761

最经典的后缀表达式简单题
https://www.luogu.com.cn/problem/P1449

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

如:3*(5–2)+7对应的后缀表达式为:3.5.2.-*7.+@。’@’为表达式的结束符号。‘.’为操作数的结束符号。

输入格式
输入:后缀表达式

输出格式
输出:表达式的值

输入输出样例
输入
3.5.2.-*7.+@
输出
16
说明/提示
字符串长度,1000内。

我写了用STL的做法,平时也可以直接用数组来模拟栈

#include<iostream>
#include<cstdio>
#include<stack>

using namespace std;

int main()
{
    
    
    stack<int> s;

    char op;
    int now = 0;

    while((op = getchar()) != '@')
    {
    
    
        if(op >= '0' && op <= '9')
            now = now * 10 + op - '0';
        else if(op == '.')
        {
    
    
            s.push(now);
            now = 0;
        }
        else if(op == '+')
        {
    
    
            int a = s.top();
            s.pop();
            int b = s.top();
            s.pop();
            s.push(b + a);
        }
        else if(op == '-')
        {
    
    
            int a = s.top();
            s.pop();
            int b = s.top();
            s.pop();
            s.push(b - a);
        }
        else if(op == '*')
        {
    
    
            int a = s.top();
            s.pop();
            int b = s.top();
            s.pop();
            s.push(b * a);
        }
        else if(op == '/')
        {
    
    
            int a = s.top();
            s.pop();
            int b = s.top();
            s.pop();
            s.push(b / a);
        }
    }

    cout << s.top();


    return 0;
}

猜你喜欢

转载自blog.csdn.net/Jerome_Chen_Y/article/details/109555293