vgsamsonov

lab2

May 25th, 2023
815
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.34 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <stack>
  4.  
  5. using namespace std;
  6.  
  7. // Функция, которая определяет приоритет операторов
  8. int priority(char c) {
  9.     if (c == '(') {
  10.         return 0;
  11.     }
  12.     if (c == '+' || c == '-') {
  13.         return 1;
  14.     }
  15.     if (c == '*' || c == '/') {
  16.         return 2;
  17.     }
  18.     return 3;
  19. }
  20.  
  21. // Функция, которая проверяет, является ли символ оператором
  22. bool isOperator(char c) {
  23.     return (c == '+' || c == '-' || c == '*' || c == '/');
  24. }
  25.  
  26. // Функция, которая проверяет, является ли выражение корректным
  27. bool isExpressionValid(string infix) {
  28.     stack<char> parentheses;
  29.     bool previousWasOperator = false;
  30.  
  31.     for (int i = 0; i < infix.length(); i++) {
  32.         char c = infix[i];
  33.         if (c == '(') {
  34.             parentheses.push(c);
  35.             previousWasOperator = false;
  36.         } else if (c == ')') {
  37.             if (parentheses.empty() || parentheses.top() != '(' || previousWasOperator) {
  38.                 return false; // Несоответствие скобок или оператор после скобки
  39.             }
  40.             parentheses.pop();
  41.             previousWasOperator = false;
  42.         } else if (isOperator(c)) {
  43.             if (previousWasOperator) {
  44.                 return false; // Два оператора подряд
  45.             }
  46.             previousWasOperator = true;
  47.         } else if (isdigit(c)) {
  48.             previousWasOperator = false;
  49.         } else if (c != ' ') {
  50.             return false; // Недопустимый символ
  51.         }
  52.     }
  53.  
  54.     return parentheses.empty() && !previousWasOperator; // Все скобки сбалансированы и выражение заканчивается операндом
  55. }
  56.  
  57. // Функция, которая преобразует инфиксное выражение в постфиксное
  58. string infixToPostfix(string infix) {
  59.     if (!isExpressionValid(infix)) {
  60.         return "Invalid expression";
  61.     }
  62.  
  63.     stack<char> operators;
  64.     string postfix;
  65.     int postfixSize = 0;
  66.     int infixSize = infix.length();
  67.  
  68.     // Динамическое выделение памяти для хранения постфиксного выражения
  69.     char* postfixArray = new char[infixSize];
  70.  
  71.     for (int i = 0; i < infixSize; i++) {
  72.         char c = infix[i];
  73.  
  74.         if (c == ' ') {
  75.             continue;
  76.         }
  77.  
  78.         if (isdigit(c)) {
  79.             postfixArray[postfixSize++] = c;
  80.         } else if (c == '(') {
  81.             operators.push(c);
  82.         } else if (c == ')') {
  83.             while (!operators.empty() && operators.top() != '(') {
  84.                 postfixArray[postfixSize++] = operators.top();
  85.                 operators.pop();
  86.             }
  87.             if (!operators.empty() && operators.top() == '(') {
  88.                 operators.pop();
  89.             }
  90.         } else if (isOperator(c)) {
  91.             while (!operators.empty() && priority(c) <= priority(operators.top())) {
  92.                 postfixArray[postfixSize++] = operators.top();
  93.                 operators.pop();
  94.             }
  95.             operators.push(c);
  96.         }
  97.     }
  98.  
  99.     while (!operators.empty()) {
  100.         postfixArray[postfixSize++] = operators.top();
  101.         operators.pop();
  102.     }
  103.  
  104.     // Преобразование динамического массива в строку
  105.     postfix = string(postfixArray, postfixSize);
  106.  
  107.     delete[] postfixArray; // Освобождение выделенной памяти
  108.  
  109.     return postfix;
  110. }
  111.  
  112. // Тесты
  113. int main() {
  114.     cout << infixToPostfix("2 + 3") << endl; // ожидаемый результат: "23+"
  115.     cout << infixToPostfix("2 * (3 + 4)") << endl; // ожидаемый результат: "234+*"
  116.     cout << infixToPostfix("2 + 3 * 4") << endl; // ожидаемый результат: "234*+"
  117.  
  118.     // Некорректные выражения
  119.     cout << infixToPostfix("2 + (3 * 4") << endl; // ожидаемый результат: "Invalid expression" (несоответствие скобок)
  120.     cout << infixToPostfix("2 + * 3") << endl; // ожидаемый результат: "Invalid expression" (ошибка в выражении)
  121.  
  122.     return 0;
  123. }
  124.  
Advertisement
Add Comment
Please, Sign In to add comment