1 #include2 #include 3 #include 4 5 using namespace std; 6 7 //获取符号的优先级 8 int getPriority(char c) 9 {10 int priority = -1;11 switch (c) {12 case '+':13 priority = 1;14 break;15 case '-':16 priority = 1;17 break;18 case '*':19 priority = 2;20 break;21 case '/':22 priority = 2;23 break;24 case '(':25 priority = 3;26 break;27 default:28 break;29 }30 return priority;31 }32 33 34 int main()35 {36 char c;37 stack s;38 cin >> c;39 while (c != '#')40 {41 while (isdigit(c))42 {43 cout << c;44 cin >> c;45 if(!isdigit(c) && c != '#')46 cout << ' ';47 48 }49 if (c == ')')50 {51 //1.弹出元素并输出直到'('52 while (s.top() != '(')53 {54 cout << s.top() << ' ';55 s.pop();56 }57 //2.将"("也出栈58 s.pop();59 }60 else61 {62 // 下面是普通操作符的情况63 // 1.弹出栈元素直到发现优先级更低的元素64 while (!s.empty() && getPriority(c) <= getPriority(s.top()) && s.top() != '(')65 {66 cout << s.top() << ' ';67 s.pop();68 }69 //将本操作符入栈70 s.push(c);71 }72 cin >> c;73 }74 while (!s.empty())75 {76 cout << s.top() << ' ' ;77 s.pop();78 }79 cout << endl;80 return 0;81 }