Answer to Question #244781 in C++ for Myname

Question #244781
Convert an infix expression to its equivalent postfix expression.
Note: The code should have the modularity and should include following functions apart from
main():
 getNextToken(): This functions returns the next token in the input infix expression. The
token may be an operator or “(“ or “)” or an operand. The operands can be of multiple
digits. For example the infix expression 1000/(10+240) contains operands 1000, 10, and
240.
 infixToPostfix(): Converts the input infix expression to postfix. This function calls
getNextToken() repeatedly to get the next token until it reaches the end. The token is
then processed depending on whether it is an operand or operator or ( or ).
1
Expert's answer
2021-09-30T07:23:34-0400


#include<iostream>
#include<stack>
using namespace std;
 


int getNextToken(char ch) {
    if(ch == '^')
        return 3;
    else if(ch == '/' || ch=='*')
        return 2;
    else if(ch == '+' || ch == '-')
        return 1;
    else
        return -1;
}
 


void infixToPostfix(string str) {
 
    stack<char> stac; 
    string re;
 
    for(int i = 0; i < str.length(); i++) {
        char ch = str[i];
 
        
        if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))
            re += ch;
 
        
        else if(ch == '(')
            stac.push('(');
 
        
        else if(ch == ')') {
            while(stac.top() != '(')
            {
                re += stac.top();
                stac.pop();
            }
            stac.pop();
        }
 
        
        else {
            while(!stac.empty() && getNextToken(str[i]) <= getNextToken(stac.top())) {
                re += stac.top();
                stac.pop(); 
            }
            stac.push(ch);
        }
    }
 
    
    while(!stac.empty()) {
        re+= stac.top();
        stac.pop();
    }
 
    cout << re << endl;
}
 


int main() {
    string expression = "1000/(10+240)";
    infixToPostfix(expression);
    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
APPROVED BY CLIENTS