Our Feeds

Wednesday 23 July 2014

Ajith KP

Conversion of Post-fix expression to In-fix expression

          The last post is about conversion of In-fix expression to Post-fix[^]. Now we are going to convert Post-fix to In-fix expression.


#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
class stacks
{
    char stack[256][256], t;
    public:
        stacks()
        {
            t=-1;
        }
        void push(char str[256])
        {
            strcpy(stack[++t], str);
        }
        char* top()
        {
            return stack[t];
        }
        void pop()
        {
            t--;
        }
        void show()
        {
            cout<<"Postfix: "<<stack[0];
        }
};

int isOperator(char c)
{
    if(c=='+'||c=='-'||c=='/'||c=='*')
    {
        return 1;
    }
    return 0;
}

int main()
{
    stacks s;
    char str[256], *ptr, tmp[256];
    cout<<"Enter string: ";
    cin>>str;
    ptr = str;
    while(*ptr!='\0')
    {
        if(isOperator(*ptr))
        {
            char *a, *b;
            a = s.top();
            s.pop();
            b = s.top();
            s.pop();
            sprintf(tmp, "%s%c%s", b, *ptr, a);
            s.push(tmp);
        }
        else
        {
            sprintf(tmp, "%c", *ptr);
            s.push(tmp);
        }
        *ptr++;
    }
    s.show();
}