Advertisement
Arnab_Manna

InfixtoPrefix

Dec 16th, 2022
532
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<ctype.h>
  4. #define MAX 100
  5.  
  6. char stack[MAX];
  7. int top = -1;
  8.  
  9. void push(char x)
  10. {
  11.     stack[++top]= x;
  12. }
  13. char pop()
  14. {
  15.     if(top == -1)
  16.         return -1;
  17.     else
  18.     {
  19.         return stack[top--];    
  20.     }  
  21. }
  22.  
  23. int prc(char x)
  24. {
  25.     if(x ==')')
  26.         return 0;  
  27.     else if(x == '^')
  28.         return 3;
  29.     else if(x =='*' || x =='/' || x=='%')
  30.         return 2;
  31.     else if(x =='+' || x =='-')
  32.         return 1;
  33. }
  34. /*
  35. int isChar(char x)
  36. {
  37.     if(x>='A' && x<='Z')
  38.         return 1;
  39.     else
  40.         return 0;
  41. }
  42. */
  43. int main()
  44. {
  45.     char exp[MAX],pri[MAX];
  46.     char *ptr,data;
  47.     int i=0;
  48.    
  49.     printf("\n Enter Exp. =");
  50.     scanf("%s",exp);
  51.     ptr=strrev(exp);
  52.    
  53.    // puts(ptr);
  54.  
  55.     while(*ptr!='\0')
  56.     {
  57.         if(isalnum(*ptr))//if(isChar(*ptr)==1)
  58.         {  
  59.             //printf("%c",*ptr);
  60.             pri[i]=*ptr;i++;
  61.         }
  62.         else if(*ptr==')')
  63.             push(*ptr);
  64.         else if(*ptr=='(')
  65.         {
  66.             while(1)
  67.                 {
  68.                     data = pop();
  69.                     if(data == ')' )
  70.                         break;  
  71.                     //printf("%c",data);
  72.                     pri[i]=data;i++;
  73.                 }
  74.         }
  75.         else
  76.         {
  77.             while(prc(stack[top]) > prc(*ptr))
  78.             {
  79.                 data = pop();
  80.                 //printf("%c",data);
  81.                 pri[i]=data;i++;
  82.             }
  83.             push(*ptr);
  84.         }  
  85.         ptr++;  
  86.     }
  87.     while(top!= -1)
  88.     {
  89.         data = pop();
  90.         //printf("%c",data);  
  91.         pri[i]=data;i++;
  92.     }
  93.    // printf("\n%s",pri);
  94.     printf("\n%s",strrev(pri));
  95.     return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement