洛谷 1449 后缀表达式 栈

https://www.luogu.org/problemnew/show/P1449

题目描述

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

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

输入输出格式

输入格式:

 

输入:后缀表达式

 

输出格式:

 

输出:表达式的值

 

输入输出样例

输入样例#1: 复制

3.5.2.-*7.+@

输出样例#1: 复制

16

说明

字符串长度,1000内。

思路:也是栈的基本应用,注意操作数可能是多位的,不一定是个位数。再注意一下减法和除法的运算顺序。

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;

int main()
{
    stack<int> s;
    char ch=getchar();
    while(ch!='@')
    {
        if(ch>='0'&&ch<='9')    //计算操作数
        {
            int temp=0;
            while(ch>='0'&&ch<='9')
            {
                temp=temp*10+ch-'0';
                ch=getchar();
            }
            s.push(temp);
        }
        else if(ch=='+')
        {
            int temp1=s.top();
            s.pop();
            int temp2=s.top();
            s.pop();
            s.push(temp1+temp2);
        }
        else if(ch=='-')
        {
            int temp1=s.top();
            s.pop();
            int temp2=s.top();
            s.pop();
            s.push(temp2-temp1);
        }
        else if(ch=='*')
        {
            int temp1=s.top();
            s.pop();
            int temp2=s.top();
            s.pop();
            s.push(temp1*temp2);
        }
        else if(ch=='/')
        {
            int temp1=s.top();
            s.pop();
            int temp2=s.top();
            s.pop();
            s.push(temp2/temp1);
        }
        ch=getchar();
    }
    cout<<s.top()<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值