我们熟悉的表达式如a+b、a+b*(c+d)等都属于中缀表达式。中缀表达式就是(对于双目运算符来说)操作符在两个操作数中间:num1 operand num2。同理,后缀表达式就是操作符在两个操作数之后:num1 num2 operand。ACM队的“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; }