ACM题目————中缀表达式转后缀

题目描述

我们熟悉的表达式如a+ba+b*(c+d)等都属于中缀表达式。中缀表达式就是(对于双目运算符来说)操作符在两个操作数中间:num1 operand num2。同理,后缀表达式就是操作符在两个操作数之后:num1 num2 operandACM队的“C小加”正在郁闷怎样把一个中缀表达式转换为后缀表达式,现在请你设计一个程序,把中缀表达式转换成后缀表达式。为简化问题,操作数均为个位数,操作符只有+-*/ 和小括号。

输入

第一行输入T,表示有T组测试数据(T<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个表达式。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。并且输入数据不会出现不匹配现象。

输出

每组输出都单独成行,输出转换的后缀表达式。

样例输入
2
1+2
(1+2)*3+4*5
样例输出
12+
12+3*45*+

温故知新啊!

还是得经常回头复习下学过的东西,很容易就会忘记了。

 

//Asimple
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <stack>
#include <cmath>
#include <string>
#include <queue>
#define INF 0xffffff
using namespace std;
const int maxn = 1000+5;
typedef long long ll ;
char str[maxn];
//操作符入栈 
stack<char> S;
//最后的结果
char ans[maxn]; 
int T, n;

int prority(char ch){
    switch(ch){
        case '+':
        case '-':
            return 1;
        case '*':
        case '/':
            return 2;
        case '(':
        case ')':
            return 0;
        default :
            return -1;
    }
}

int main(){
    scanf("%d",&T);
    S.push('#');
    while( T -- ){
        scanf("%s",str);
        n = 0;
        for(int i=0; i<strlen(str); i++){
            if( str[i] >= '0' && str[i] <= '9' ){//数字
                ans[n++] = str[i];
            } else if( str[i] == ')' ){// 右括号 
                while( S.top() != '(' ){//直到找到左括号 
                    ans[n++] = S.top();
                    S.pop();
                }
                S.pop();//弹出左括号 
                } else if( str[i] == '(' ){
                    S.push(str[i]);//左括号入栈 
                } else{// + - * / 操作符的处理 
                 if( prority(str[i]) > prority(S.top())){
                 S.push(str[i]);
                 } else{
                     while( prority(str[i])<=prority(S.top()) ){
                         ans[n++] = S.top();
                         S.pop();
                     }
                 S.push(str[i]);
                 }
            }
        }
        while( S.top()!= '#' ){
            ans[n++] = S.top();
            S.pop();
        }
        ans[n] = '\0';
        puts(ans);
    }
    return 0;
}       

 

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
06-13 10:15
门头沟学院 Java
想去夏威夷的大西瓜在...:我也是27届,但是我现在研一下了啥项目都没有呀咋办,哎,简历不知道咋写
点赞 评论 收藏
分享
06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务