NYOJ 中缀式变成后缀式(栈)

来源:互联网 发布:好用的会计软件 编辑:程序博客网 时间:2024/06/04 00:34

中缀式变后缀式

时间限制:1000 ms  |  内存限制:65535 KB
难度:3
描述
人们的日常习惯是把算术表达式写成中缀式,但对于机器来说更“习惯于”后缀式,关于算术表达式的中缀式和后缀式的论述一般的数据结构书都有相关内容可供参看,这里不再赘述,现在你的任务是将中缀式变为后缀式。
输入
第一行输入一个整数n,共有n组测试数据(n<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式的中缀式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。
数据保证除数不会为0
输出
每组都输出该组中缀式相应的后缀式,要求相邻的操作数操作符用空格隔开。
样例输入
21.000+2/4=((1+2)*5+1)/4=
样例输出
1.000 2 4 / + =

1 2 + 5 * 1 + 4 / =

#include <iostream> #include <string> #include <stack> using namespace std;int cmp(char ch) {switch (ch){case '+':case '-': return 1;case '*':case '/': return 2;default: return 0;}}void change(string &s1, string &s2) {stack <char > s;s.push('#');int i = 0;while (i <=s1.length() - 2){if (s1[i] == '('){s.push(s1[i++]);}else if (s1[i] == ')'){while (s.top() != '('){s2 += s.top();s2 += ' ';s.pop();}s.pop();i++;}else if (s1[i] == '+' || s1[i] == '-' || s1[i] == '*' || s1[i] == '/'){while (cmp(s.top()) >= cmp(s1[i])){s2 += s.top();s2 += ' ';s.pop();}s.push(s1[i]);i++;}else{while ('0' <= s1[i] && s1[i] <= '9' || s1[i] == '.'){s2 += s1[i];i++;}s2 += ' ';}}while (s.top() != '#'){s2 += s.top();s2 += ' ';s.pop();}s2 += '=';}int main(){int n;string s1, s2;cin >> n;while (n--){cin >> s1;s2 = " ";change(s1, s2);cout << s2 << endl;}return 0;}


原创粉丝点击