LAB_05
Task04
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int precedence(char c) {
if (c == '^') return 3;
if (c == '*' || c == '/') return 2;
if (c == '+' || c == '-') return 1;
return 0;
}
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
bool isOperand(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
bool isLeftAssociative(char c) {
return !(c == '^');
}
string infixToPostfix(const string& infix) {
stack<char> s;
string postfix = "";
for (char c : infix) {
if (isOperand(c)) {
postfix += c;
}
else if (c == '(') {
s.push(c);
}
else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop();
}
else if (isOperator(c)) {
while (!s.empty() && precedence(s.top()) >= precedence(c) &&
isLeftAssociative(c)) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
string postfixToInfix(const string& postfix) {
stack<string> s;
for (char c : postfix) {
if (isOperand(c)) {
s.push(string(1, c));
}
else {
string operand2 = s.top(); s.pop();
string operand1 = s.top(); s.pop();
string infix = "(" + operand1 + c + operand2 + ")";
s.push(infix);
}
}
return s.top();
}
string prefixToPostfix(const string& prefix) {
stack<string> s;
for (int i = prefix.size() - 1; i >= 0; i--) {
char c = prefix[i];
if (isOperand(c)) {
s.push(string(1, c));
}
else {
string operand1 = s.top(); s.pop();
string operand2 = s.top(); s.pop();
string postfix = operand1 + operand2 + c;
s.push(postfix);
}
}
return s.top();
}
int main() {
string infix = "a+b*(c^d-e)^(f+g*h)-I";
cout << "Infix: " << infix << endl;
cout << "Postfix: " << infixToPostfix(infix) << endl;
string postfix = "abc++";
cout << "Postfix: " << postfix << endl;
cout << "Infix: " << postfixToInfix(postfix) << endl;
string prefix = "*+AB-CD";
cout << "Prefix: " << prefix << endl;
cout << "Postfix: " << prefixToPostfix(prefix) << endl;
return 0;
}