#include <iostream>
#include <stack>
#include <cctype>
using namespace std;
int precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
if (op == '^') return 3;
return 0;
}
bool isRightAssociative(char op) {
return op == '^';
}
bool isOperator(char op) {
return (op == '+' || op == '-' || op == '*' || op == '/' || op == '^');
}
string infixToPostfix(string infix) {
stack<char> st;
string postfix = "";
for (char &c : infix) {
if (isalnum(c)) {
postfix += c; // operand directly goes to output
}
else if (c == '(') {
st.push(c);
}
else if (c == ')') {
while (!st.empty() && st.top() != '(') {
postfix += st.top();
st.pop();
}
if (!st.empty()) st.pop(); // remove '('
}
else if (isOperator(c)) {
while (!st.empty() && precedence(st.top()) > 0) {
if ((!isRightAssociative(c) && precedence(c) <= precedence(st.top())) ||
(isRightAssociative(c) && precedence(c) < precedence(st.top()))) {
postfix += st.top();
st.pop();
}
else break;
}
st.push(c);
}
}
// Pop remaining operators
while (!st.empty()) {
postfix += st.top();
st.pop();
}
return postfix;
}
int main() {
string infix;
cout << "Enter Infix Expression: ";
cin >> infix;
string postfix = infixToPostfix(infix);
cout << "Postfix Expression: " << postfix << endl;
return 0;
}
No comments:
Post a Comment