首页 > 其他 > 详细

后缀表达式(逆波兰表达式)

时间:2019-07-23 23:00:02      阅读:91      评论:0      收藏:0      [点我收藏+]

题目描述

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

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

输入输出格式

输入格式:

 

输入:后缀表达式

 

输出格式:

 

输出:表达式的值

 

输入输出样例

输入样例#1: 复制
3.5.2.-*7.+@
输出样例#1: 复制
16

说明

字符串长度,1000内。

算法:栈

#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
int num,k;
typedef long long LL;
int cal(string &s){
    stack<LL>stk;
    for(int i=0;s[i]!=@;i++){
        if(s[i]==.){
            int j=i-1;
            num=0,k=1;
            while(j>=0&&s[j]>=0&&s[j]<=9){
                num+=(s[j]-0)*k;
                k*=10;
                j--;
            }
            stk.push(num);
            continue;
        }
        if(s[i]>=0&&s[i]<=9)continue;
        if(s[i]==+){
            int a=stk.top();
            stk.pop();
            int b=stk.top();
            stk.pop();
            stk.push(a+b);
        }else if(s[i]==-){
            int a=stk.top();
            stk.pop();
            int b=stk.top();
            stk.pop();
            stk.push(b-a);
        }else if(s[i]==*){
            int a=stk.top();
            stk.pop();
            int b=stk.top();
            stk.pop();
            stk.push(b*a);
        }else if(s[i]==/){
            int a=stk.top();
            stk.pop();
            int b=stk.top();
            stk.pop();
            stk.push(b/a);
        }
    }
    return stk.top();
}
int main(void){
    string s;
    cin>>s;
    cout<<cal(s)<<endl;
    return 0;
}

 

后缀表达式(逆波兰表达式)

原文:https://www.cnblogs.com/programyang/p/11234933.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!