C++题目_中缀表达式转后缀表达式(常考)

时间限制: 1.0 Sec 内存限制: 128 MB

题目描述

给定一个中缀表达式,请你输出其对应的后缀表达式

输入

输入一行字符串 s (|s| ≤ 100)表示一个合法的中缀表达式,且其中的数字都在INT范围内,同时也保证只会出现 +,-,*,/, (,) 这几种符号。

输出

输出一行,表示该中缀表达式所对应的后缀表达式,中间用空格隔开。

样例输入1 复制
复制代码
9+(3-11)*3+8/2 
样例输出1 复制
复制代码
9 3 11 - 3 * + 8 2 / +

题目链接:hat8.zemeitong.cn/askai/1002?channel=bdtoufangztAskHD5

代码:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
string s;
stack<char> st;
int main()
{
    cin>>s;
    map<char, int>mp = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
    for(int i = 0; i < s.length(); i ++)
    {
        if(isdigit(s[i]))
        {
            int j = i;
            int val = 0;
            while(j < s.length() && isdigit(s[j]))
            {
                val = val * 10 + s[j] - '0';
                j ++;
            }
            i = j - 1;
            cout<<val<<" ";
        }
        else
        {
            if(s[i] == '(')
            {
                st.push('(');
            }
            else if(s[i] == ')')
            {
                while(st.top() != '(')
                {
                    cout<<st.top()<<" ";
                    st.pop();
                }
                st.pop();
            }
            else
            {
                while(st.size() > 0 && st.top() != '(' && mp[st.top()] >= mp[s[i]])
                {
                    cout<<st.top()<<" ";
                    st.pop();
                }
                st.push(s[i]);
            }
        }
    }
    while(st.size())
    {
        cout<<st.top()<<" ";
        st.pop();
    }
    return 0;
}
相关推荐
柯一梦几秒前
STL2---深入探索vector的实现
c++
风暴之零7 分钟前
变点检测算法PELT
算法
深鱼~7 分钟前
视觉算法性能翻倍:ops-cv经典算子的昇腾适配指南
算法·cann
李斯啦果8 分钟前
【PTA】L1-019 谁先倒
数据结构·算法
MSTcheng.8 分钟前
【C++】C++11新特性(二)
java·开发语言·c++·c++11
晓131311 分钟前
第七章 【C语言篇:文件】 文件全面解析
linux·c语言·开发语言
愚者游世11 分钟前
Delegating Constructor(委托构造函数)各版本异同
开发语言·c++·程序人生·面试·改行学it
小镇敲码人13 分钟前
探索华为CANN框架中的ACL仓库
c++·python·华为·acl·cann
梵刹古音14 分钟前
【C语言】 指针基础与定义
c语言·开发语言·算法
Ekehlaft17 分钟前
这款国产 AI,让 Python 小白也能玩转编程
开发语言·人工智能·python·ai·aipy