NYOJ 467中缀式变后缀式

 1 中缀式变后缀式
 2 
 3  时间限制:1000 ms  |  内存限制:65535 KB 
 4 
 5 难度:3
 6 
 7 描述 人们的日常习惯是把算术表达式写成中缀式,但对于机器来说更“习惯于”后缀式,关于算术表达式的中缀式和后缀式的论述一般的数据结构书都有相关内容可供参看,这里不再赘述,现在你的任务是将中缀式变为后缀式。
 8 输入第一行输入一个整数n,共有n组测试数据(n<10)。
 9  每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式的中缀式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。
10  数据保证除数不会为0输出每组都输出该组中缀式相应的后缀式,要求相邻的操作数操作符用空格隔开。样例输入2
11 1.000+2/4=
12 ((1+2)*5+1)/4=样例输出1.000 2 4 / + =
13 1 2 + 5 * 1 + 4 / =
14 
15 
16 #include<iostream>
17 #include<stack>
18 using namespace std;
19 
20 bool isNum(char c)
21 {
22     if((c>='0' && c<='9') || c == '.')
23         return true;
24     return false;
25 }
26 
27 bool cmp(char c1,char c2)
28 {
29     if(c2 == '(' || c1 == '(' || c2 == '#'return true;
30     else if( (c1 == '*' || c1 == '/') && (c2 == '+' || c2 == '-') ) return true;
31     return false;
32 }
33 
34 int main()
35 {
36 //    freopen("in.txt","r",stdin);
37     int i,j,t;
38     cin>>t;
39     stack<char> st;
40     st.push('#');
41     char a[1010],num[50];
42     while(t--){
43         cin>>a;
44         for(i=0; a[i]!='\0'; ++i){
45             if(isNum(a[i])){
46                 j = 0;
47                 while(isNum(a[i]))
48                     num[j++] = a[i++];
49                 num[j] = '\0';
50                 cout<<num<<" ";
51                 --i;
52             }
53             else{
54                 if( cmp(a[i], st.top()) ){
55                     if(a[i] == ')' && st.top() == '(')
56                         st.pop();
57                     else
58                         st.push(a[i]);
59                 }
60                 else{
61                     if(a[i] == ')'){
62                         while(st.top() != '('){
63                             cout<<st.top()<<" ";
64                             st.pop();
65                         }
66                         st.pop();
67                     }
68                     else if(a[i] == '='){
69                         while(st.top() != '#'){
70                             cout<<st.top()<<" ";
71                             st.pop();
72                         }
73                         cout<<"=\n";
74                     }
75                     else{    
76                         while(!cmp(a[i],st.top())) //要考虑一种情况:1+2*5-6=    
77                         {
78                             cout<<st.top()<<" ";
79                             st.pop();
80                         }
81                         st.push(a[i]);
82                     }
83                 }
84             }
85         }
86     }
87     return 0;
88 }
原文地址:https://www.cnblogs.com/yaling/p/3002347.html