C++ program for postfix conversions - C C++ Java Programs - Examples

Latest

C C++ Java Python Perl Programs Examples with Output -useful for Schools & College Students

Monday, April 4, 2011

C++ program for postfix conversions


#include<iostream.h>
#include<conio.h>
#include<string.h>

char *infix,*postfix,*stack,c;
int length,counti,countp,top=-1,tmp;

int post(void )
{
   int i;
   for(i=0;i<length;i++)
 if((infix[i]=='(')||(infix[i]==')'))
tmp++;
   tmp=length-tmp;
   //countp=tmp;
   stack=new char[length-tmp];
   postfix=new char[countp];

   for(counti=0;counti<length;counti++)
   {
 c=infix[counti];
 if(((c>47)&&(c<58))||((c>64)&&(c<91))||((c>96)&&(c<123)))
postfix[countp++]=c;

 if(c=='(')
stack[++top]=c;

 if(c=='^')
stack[++top]=c;

 if((c=='+')||(c=='-'))
 {
while((stack[top]=='^')||(stack[top]=='*')||(stack[top]=='/')||(stack[top]=='-'))
postfix[countp++]=stack[top--];
stack[++top]=c;
 }

 if((c=='*')||(c=='/'))
 {
while((stack[top]=='^')||(stack[top]=='*')||(stack[top]=='/'))
postfix[countp++]=stack[top--];
stack[++top]=c;
 }

 if(c==')')
 {
while(stack[top]!='(')
postfix[countp++]=stack[top--];
top--;
 }
   }
   while(top>-1)
 postfix[countp++]=stack[top--];

   cout<<"\n\nPostfix expression is : \n";

   for(i=0;i<tmp;i++)
 cout<<postfix[i];
   return 0;
}



int main()
{
   int i=0;
   cout<<"\nEnter the infix expression : \n";
   cin>>infix;

   length=strlen(infix);
   //infix=new char[length];
  
  
   post();
   getch();
   return 0;
}

No comments:

Post a Comment