题目链接:http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=257
时间限制:1000 ms | 内存限制:65535 KB
难度:3
描述
我们熟悉的表达式如a+b、a+b*(c+d)等都属于中缀表达式。中缀表达式就是(对于双目运算符来说)操作符在两个操作数中间:num1 operand num2。同理,后缀表达式就是操作符在两个操作数之后:num1 num2 operand。ACM队的“C小加”正在郁闷怎样把一个中缀表达式转换为后缀表达式,现在请你设计一个程序,帮助C小加把中缀表达式转换成后缀表达式。为简化问题,操作数均为个位数,操作符只有+-*/ 和小括号。
输入
第一行输入T,表示有T组测试数据(T<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个表达式。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。并且输入数据不会出现不匹配现象。
输出
每组输出都单独成行,输出转换的后缀表达式。
样例输入
2
1+2
(1+2)*3+4*5
样例输出
12+
12+3*45*+
分析: 中缀表达式转后缀表达式(逆波兰式),由于涉及的操作符比较少,我们可以不用单独为操作符设置优先级。可简单按如下操作处理:
- 遇到操作数,直接输出(添加到后缀表达式中)
- 遇到左括号,入栈
- 遇到右括号,执行出栈操作,并见出栈的元素输出,直到弹出栈的是左括号,左括号不输出
- 遇到加减乘除(优先级:乘除>加减),弹出所有优先级大于或等于该op的op,然后该op入栈
- 出栈时注意在栈非空时进行
- 最终将栈中元素依次出栈,输出
#include <cstdio>
#include <iostream>
#include <stack>
using namespace std;
const int LEN = 1005;
char nifix_expre[LEN];
stack<char> cs;
void Solve() {
for (int i = 0; nifix_expre[i]; i++) {
if (nifix_expre[i] >= '0' && nifix_expre[i] <= '9') {
putchar(nifix_expre[i]); //遇到数字直接输出
}
else if (nifix_expre[i] == '(') cs.push(nifix_expre[i]); //左括号直接入栈
else if (nifix_expre[i] == ')') {
//输出栈中最前的'('之前的op(小括号存在嵌套,所以强调'最前')
while (cs.top() != '(') {
putchar(cs.top());
cs.pop();
}
cs.pop();
}
else if (nifix_expre[i] == '*' || nifix_expre[i] == '/') {
if (!cs.empty()) { //考虑栈是否为空
if (cs.top() == '*' || cs.top() == '/') { //弹出优先级相等的op
putchar(cs.top());
cs.pop();
}
}
cs.push(nifix_expre[i]);
}
else {
while (!cs.empty()) {
//弹出栈中所有优先级大于等于当前op的op
if (cs.top() != '(' && cs.top() != ')') {
putchar(cs.top());
cs.pop();
}
else break;
}
cs.push(nifix_expre[i]);
}
}
while (!cs.empty()) { //栈中op出栈
putchar(cs.top());
cs.pop();
}
putchar('\n');
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
scanf("%s", nifix_expre);
Solve();
}
return 0;
}
参照:https://www.cnblogs.com/mygmh/archive/2012/10/06/2713362.html