Header Ads

Infix to postfix converting using stack and queue in C++.

 Problem: Infix to postfix converting using stack and queue in C++.


#include<iostream>

#include<stack>

#include<queue>

using namespace std;

int priority(char op){

    if(op == '+' || op == '-')

    {

        return 1;

    }                                 /* This method have used for

                                         assign operator value.

                                         */

    if(op == '*' || op == '/')

    {

        return 2;

    }

    if(op=='^')

    {

        return 3;

    }

    return 0;

}


int main(){

    stack <char> st;

    queue <char> infix,postfix;   // This is used for to store character on infix and postfix


    infix.push('(');

    //read infix expression


    cout<<"Enter your Infix expression: ";

    char s,t;

    while(1){

        cin.get(s);

        if(s == ' ')continue;

        if(s == '\n')break;

        infix.push(s);

    }

    infix.push(')');

    //convert to postfix

    while(!infix.empty()){

        s = infix.front();

        infix.pop();

        //check for operator

        if(s == '+' || s == '-' || s == '*' || s=='/' || s=='^'){

            while(priority(st.top()) >= priority(s) ){

                t = st.top();

                postfix.push(t);

                st.pop();


            }

            st.push(s);    //push operator on top

        }

        else if(s == '('){

            st.push(s);

        }

        else if(s == ')'){

            t= st.top();

            st.pop(); // if have first brackets on top element of stack then pop this.

            while(t != '('){

                postfix.push(t);

                t=st.top();

                st.pop();

            }

        }

        else{//for operand

            postfix.push(s);

        }

    }

    //print postfix expression

    cout<< ""<<"Your Postfix expression is: ";

    // Printing content of queue

    while (!postfix.empty()) {

        cout << ' ' << postfix.front();

        postfix.pop();

    }

    cout<<endl;


    return 0;

}

Console output:




No comments

Powered by Blogger.