Answer to Question #284012 in C++ for ahmed

Question #284012

If you have the

following expression:



(( A * (B + D)/E) - F * (G + H / K)))



Write C++ Program to convert infix

to postfix expression using the Stack Data Structure



1
Expert's answer
2021-12-31T15:43:28-0500
#include <iostream>
#include <string>
#include <stack>
using namespace std;


int prec(char c) {
    switch(c){
        case '^': return 3;
        case '/':;
        case '*':return 2;
        case '+':;
        case '-': return 1;
        default: return -1;
    }
}
 


void convertToPostfix(string s) {
 
    stack<char> st;
    string result;
 
    for(int i = 0; i < s.length(); i++) {
        char c = s[i];
 
        if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
            result += c;
 
        else if(c == '(')
            st.push('(');
 
        else if(c == ')') {
            if(!st.empty()){
                while(st.top() != '(')
                {
                    result += st.top();
                    st.pop();
                }
                st.pop();
            }
        }
 
        else {
            while(!st.empty() && prec(s[i]) <= prec(st.top())) {
                result += st.top();
                st.pop(); 
            }
            st.push(c);
        }
    }


    while(!st.empty()) {
        result += st.top();
        st.pop();
    }
 
    cout << result << endl;
}
 
int main() {
    string expr = "((A*(B+D)/E)-F*(G+H/K)))";
    convertToPostfix(expr);
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog