Tutorials, Free Online Tutorials,It Challengers provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, core java, sql, php, c language etc. for beginners and professionals.

Breaking

Data Structure - Conversion of Infix to Post-fix

------------------------------------------ " Data Structure "---------------------------------------
STACK
 Infix to Post-fix 
#include<stdio.h> 
#include<conio.h>

#define maxm 100
 char stack[maxm];
 int top=-1,bottom=-1;
 void push();
 char pop();
 int isempty();
 int isfull(); 
 int priority(); 

 //IsEmpty function

int isempty()
 { 
 if(top==bottom)
     return 1;
 else
     return 0;
 }

 //isFull function

 int isfull()
 {
if(top==maxm-1) 
      return 1;
  else
 return 0;
  }
  
 //Push function
  void push(char x)
  { 
    if(isfull()!=1) 
      { 
      top=top+1; 
      stack[top]=x; 
      }
  }

 //Pop function  
  char pop()
 {
 if(isempty()!=1)
 return(stack[top--]); 
      } 
 //check Priority function
int priority(char ch) 
 {
if(ch=='^')
return 3;
if(ch=='*'||ch=='/'||ch=='%') 
      return 2;
     if(ch=='+'||ch=='-')
 return 1;
     else 
      return 0; 
 } 

  //Main function

void main()
 { 
     char str[80],post[80]=" ",tos; 
     int i,j=0,k; 
     clrscr(); 
     printf("Enter Infix Expression : \n");
     scanf("%s",str); 
     printf("\nScan character\t\tStack\t\tPostfix Expression");
for(i=0;i<strlen(str);i++) 
               printf("\n%c\t\t",str[i]); 
if(isalpha(str[i])||isdigit(str[i])) 
  {
 post[j]=str[i];
 j++;   
   post[j]='\0';
 for(k=0;k<=top;k++)
             printf("%c",stack[k]);
       printf("\t\t%s",post); 
 
    else 
switch(str[i]) 
case '(' : push(str[i]); 
  for(k=0;k<=top;k++)
printf("%c",stack[k]); 
  printf("\t\t%s",post);
break; 
 
case ')' : while(1) 
  {
tos=pop();
if(tos=='(')
break; 
else 
  post[j]=tos;
  j++; 
for(k=0;k<=top;k++) 
printf("%c",stack[k]); 
printf("\t\t%s",post); 
  break;
case '+' :
case '-' :
case '*' :
case '/' :
case '%' : 
case '^' :
if(stack[top]=='(') 
  push(str[i]);
for(k=0;k<=top;k++)
printf("%c",stack[k]); 
  printf("\t\t%s",post);
break; 
  if(priority(str[i])>priority(stack[top]))
push(str[i]); 
else 
 while(isempty()==0&&(priority(str[i])<=priority(stack[top]))) 
 { 
      tos=pop();
    post[j]=tos;
    j++;
 } 
push(str[i]); 
  for(k=0;k<=top;k++)
printf("%c",stack[k]);
printf("\t\t%s",post); 
break; 
}//end of switch 
   }//end of else 
}//end of for() 
printf("\n\\0\t\t"); 
while(isempty()!=1) 
{
    tos=pop(); 
post[j++]=tos; 
  post[j]='\0';
printf("\t\t%s",post);
printf("\n\nPostfix expression of given Infix Expression : %s",post);
getch(); 


No comments:

Post a Comment