fork download
  1. #include <iostream>
  2. #include <stack>
  3. #include <string>
  4. #include <sstream>
  5. #include <cctype>
  6. #include <vector>
  7. #include <map>
  8.  
  9. using namespace std;
  10.  
  11. // Пріоритети операторів
  12. map<char, int> precedence = {
  13. {'+', 1}, {'-', 1},
  14. {'*', 2}, {'/', 2},
  15. {'(', 0} // Дужки мають найнижчий пріоритет
  16. };
  17.  
  18. // Функція перевірки, чи символ є оператором
  19. bool isOperator(char c) {
  20. return precedence.count(c) > 0;
  21. }
  22.  
  23. // Перетворення інфіксного виразу в постфіксний
  24. string infixToPostfix(const string& infix) {
  25. stack<char> operators;
  26. stringstream output;
  27.  
  28. for (size_t i = 0; i < infix.length(); i++) {
  29. char token = infix[i];
  30.  
  31. // Якщо символ — число або літера, додаємо його у вихідний рядок
  32. if (isalnum(token)) {
  33. output << token;
  34. }
  35. // Якщо символ — оператор
  36. else if (isOperator(token)) {
  37. while (!operators.empty() && precedence[operators.top()] >= precedence[token]) {
  38. output << ' ' << operators.top();
  39. operators.pop();
  40. }
  41. output << ' ';
  42. operators.push(token);
  43. }
  44. // Якщо символ — відкрита дужка, додаємо в стек
  45. else if (token == '(') {
  46. operators.push(token);
  47. }
  48. // Якщо символ — закрита дужка, обробляємо стек
  49. else if (token == ')') {
  50. while (!operators.empty() && operators.top() != '(') {
  51. output << ' ' << operators.top();
  52. operators.pop();
  53. }
  54. operators.pop(); // Видаляємо '('
  55. }
  56. }
  57.  
  58. // Витягуємо залишки операторів зі стеку
  59. while (!operators.empty()) {
  60. output << ' ' << operators.top();
  61. operators.pop();
  62. }
  63.  
  64. return output.str();
  65. }
  66.  
  67. int main() {
  68. string infix = "3+4*2/(1-5)";
  69. cout << "Інфіксний запис: " << infix << endl;
  70. cout << "Постфіксний запис: " << infixToPostfix(infix) << endl;
  71. return 0;
  72. }
  73.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Інфіксний запис: 3+4*2/(1-5)
Постфіксний запис: 3 4 2 *  / + 1 5 -