infix to postfix

 avatar
user_9350232
plain_text
9 months ago
1.7 kB
11
Indexable
#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;

int precedence(char c) {
    if (c == '+' || c == '-') return 1;
    if (c == '*' || c == '/') return 2;
    if (c == '^') return 3;
    return 0;
}

// ---------- INFIX TO POSTFIX ----------
string infixToPostfix(string s) {
    stack<char> st;
    string result;
    for (char c : s) {
        if (isalnum(c))
            result += c;
        else if (c == '(')
            st.push(c);
        else if (c == ')') {
            while (!st.empty() && st.top() != '(') {
                result += st.top();
                st.pop();
            }
            st.pop(); // remove '('
        } else {
            while (!st.empty() && precedence(st.top()) >= precedence(c)) {
                result += st.top();
                st.pop();
            }
            st.push(c);
        }
    }
    while (!st.empty()) {
        result += st.top();
        st.pop();
    }
    return result;
}

// ---------- INFIX TO PREFIX ----------
string infixToPrefix(string s) {
    reverse(s.begin(), s.end());
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == '(') s[i] = ')';
        else if (s[i] == ')') s[i] = '(';
    }
    string postfix = infixToPostfix(s);
    reverse(postfix.begin(), postfix.end());
    return postfix;
}

// ---------- MAIN ----------
int main() {
    string exp;
    cout << "Enter infix expression: ";
    cin >> exp;

    cout << "Postfix Expression: " << infixToPostfix(exp) << endl;
    cout << "Prefix Expression: " << infixToPrefix(exp) << endl;

    cout << "\nTime Complexity: O(n)\nSpace Complexity: O(n)\n";
    return 0;
}
Editor is loading...
Leave a Comment