Infix to Postfix conversion of an expression


#include<stdio.h>
#include<iostream>
#include<string.h>
#include<queue>
#include<stack>
using namespace std;
class infixtoprefix
{
    int len;
    char strn[100];
    stack<char> stackk;
    queue<char> strng;

    public:
    infixtoprefix()
    {
        cin>>strn;
        len=strlen(strn);
    }

    int priority(char a)
    {
        if(a=='*'||a=='/')
        {
            return 2;
        }
        else if(a=='+'||a=='-')
        {
            return 1;
        }
        else
         return 0;
    }

    int convert()
    {
        int i=0;
        int k=0;
        while(i<len)
        {
///case 1
            if(isalpha(strn[i])||isdigit(strn[i])) // if its an alophabet or digit i.ie., a to z and 1 to 9
            {
                 strng.push(strn[i]);
            }
///case 2
            else if(strn[i]==')')
            {
                while(stackk.top()!='(')
                {
                    strng.push(stackk.top());
                    stackk.pop();
                }
                stackk.pop();
            }
///case 3
            else //if its an operator i.e., +,-,*,/
            {
                if(stackk.empty()||(priority(stackk.top())<priority(strn[i]))) //if stack is empty or priority of element in stack is lower
                {
                    stackk.push(strn[i]);
                }
                else
                {
                    while(!stackk.empty()&&stackk.top()!='('&&priority(stackk.top())>priority(strn[i]))
                    {
                        char topvalue=stackk.top();
                        stackk.pop();
                        strng.push(topvalue);
                    }
                    stackk.push(strn[i]);
                }
            }
            i++;
        }

        while(!stackk.empty())
        {
            strng.push(stackk.top());
            stackk.pop();
        }
    }

    void display()
    {
        while(!strng.empty())
        {
            cout<<strng.front();
            strng.pop();
        }
    }
};

int main()
{
    infixtoprefix *obj = new infixtoprefix();
    obj->convert();
    obj->display();
}

Comments

Popular Posts