Tuesday 3 November 2015

CPP Program for converting infix expression into postfix expression - Data Structures

#include<iostream>
using namespace std;
char s[100],top=-1;
void push(char val)
{
s[++top]=val;
}
char pop()
{char cc;
cc=s[top];
top--;
return cc;
}

int isempty()
{
if(top==-1)
return 1;
}

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

int main()
{
char a[20],c,tptk,t;
int i=0;
cout<<"\nEnter the infix:";
cin>>a;
cout<<"\nPostfix:";
while(a[i]!='\0')
{
c=a[i];
if(c=='(')
push('(');
else if(c==')')
{
    c=pop();
  while(c!='(')
   {
     
      cout<<c;
       c=pop();
    }
}
else if(c=='*'||c=='/'||c=='+'||c=='-')
{
tptk=s[top];
while(!isempty() && priority(c)<=priority(tptk))
{t=pop();
 cout<<t;
  tptk=s[top];
}
push(c);
}
else
cout<<c;
i++;
}

while(!isempty())
{
c=pop();
cout<<c;
}
return 0;
}


OUTPUT:
Enter the infix:(a+b)*(c-d)/e

Postfix:ab+cd-*e/


Enter the infix:2+4

Postfix:24+

No comments:

Post a Comment