Computer Scientists are Pretty Pessimistic

Thursday 11 August 2016

Conversion of an Infix expression into Postfix expression


Algorithm : :
S <- empty stack
S <- ‘#’
j <- 0
i <- 0
Append '$' sign at last of the expression
while top(s) ≠ ‘$’ do
        Case:
           E[i] is an operand or number :
                      j <- j+1
                      P[j] <- E[i]
            E[i] = ‘(‘ :
                      S <= E[i]
            E[i] = ‘)’ :
                      x <= S
                      while x ≠ ‘(‘ do
                           j <- j+1
                           P[j] <- x
                           x <= S
             E[i] is an operator :
                       while prec(E[i]) ≤ prec(top(S)) do
                                 j <- j+1
                                 P[j] <=S
                                  S <= E[i]
        i <- i+1


Precedency Table
Character
Precedency
#
0
$
1
(
2
+ , -
3
*,  /
4
^
5

CODE :: 

#include <iostream>
#include <map>
#include <stack>
#include <cstdio>
#include <cstring>
using namespace std;
int prec(char c)
{
    map<char,int>mp;
    mp['#']=0;
    mp['$']=1;
    mp['(']=2;
    mp['+']=3;  mp['-']=3;
    mp['*']=4;  mp['/']=4;
    mp['^']=5;
    return mp[c];
}
int main()
{
    char E[10000],P[10000];
    stack<char>st;
    st.push('#');
    int j=0,i=0;
    gets(E);
    strcat(E,"$");
    while(st.top()!='$')
    {
        if(isalpha(E[i]))
        {
            P[j++] = E[i];
        }
        else if(E[i]=='(')
        {
            st.push(E[i]);
        }
        else if(E[i]==')')
        {
            char x = st.top(); st.pop();
            while(x!='(')
            {
                P[j++] = x;
                x = st.top(); st.pop();
            }
        }
        else
        {
            while(prec(E[i])<=prec(st.top()))
            {

                P[j++] = st.top(); st.pop();
            }
            st.push(E[i]);
        }
        i++;
    }
    for(int i=0;i<j;i++)
        cout<<P[i];
    cout<<endl;
}

No comments:

Post a Comment