fork download
  1. #include <iostream>
  2. #include <stack>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. bool hasHigherPreference(char s_top, char c){
  8.  
  9. if ((c == '*' || c== '/') && (s_top == '+' || s_top == '-'))
  10. return true;
  11.  
  12. return false;
  13. }
  14.  
  15. bool isOperator(char c){
  16.  
  17. if (c == '+' || c == '-' || c == '*' || c== '/')
  18. return true;
  19.  
  20.  
  21. return false;
  22.  
  23. }
  24. int main() {
  25. int t;
  26. char c;
  27. stack<char> s;
  28. string postfix = "";
  29.  
  30. cin >> t;
  31. cin.ignore(1000, '\n');
  32.  
  33. while (t--) {
  34. cin.ignore(1000, '\n');
  35.  
  36. while (cin.peek() != '\n' && cin.peek() != -1) {
  37. cin >> c;
  38. cin.ignore(100, '\n');
  39.  
  40. if (c == '(')
  41. s.push(c);
  42. else if(c==')'){
  43. while(s.top() != '('){
  44. postfix += s.top();
  45. s.pop();
  46. }
  47. s.pop();
  48. } else if (!isOperator(c)) {
  49. postfix += c;
  50. } else if (s.empty() || hasHigherPreference(s.top(),c)){
  51. s.push(c);
  52. } else {
  53. postfix += s.top();
  54. s.pop();
  55. s.push(c);
  56. }
  57. }
  58.  
  59. while(!s.empty()){
  60. postfix += s.top();
  61. s.pop();
  62. }
  63.  
  64.  
  65.  
  66. cout << postfix << endl;
  67. }
  68. }
Success #stdin #stdout 0.02s 4472KB
stdin
Standard input is empty
stdout