Advertisement
sol4r

Infix TO Postfix In C

Mar 13th, 2023
827
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.02 KB | None | 0 0
  1. #include<stdio.h>
  2. char stack[100];
  3. int top = -1;
  4. void push(char x)
  5. {
  6.     stack[++top] = x;
  7. }
  8.  
  9. char pop()
  10. {
  11.     if(top == -1)
  12.         return -1;
  13.     else
  14.         return stack[top--];
  15. }
  16. int priority(char x)
  17. {
  18.     if(x == '(')
  19.         return 0;
  20.     if(x == '+' || x == '-')
  21.         return 1;
  22.     if(x == '*' || x == '/')
  23.         return 2;
  24.     return 0;
  25. }
  26.  
  27. int main()
  28. {
  29.     char exp[100];
  30.     char *e, x;
  31.     printf("Enter the expression : ");
  32.     scanf("%s",exp);
  33.     printf("\n");
  34.     e = exp;
  35.  
  36.     while(*e != '\0')
  37.     {
  38.         if(isalnum(*e))
  39.             printf("%c ",*e);
  40.         else if(*e == '(')
  41.             push(*e);
  42.         else if(*e == ')')
  43.         {
  44.             while((x = pop()) != '(')
  45.                 printf("%c ", x);
  46.         }
  47.         else
  48.         {
  49.             while(priority(stack[top]) >= priority(*e))
  50.                 printf("%c ",pop());
  51.             push(*e);
  52.         }
  53.         e++;
  54.     }
  55.  
  56.     while(top != -1)
  57.     {
  58.         printf("%c ",pop());
  59.     }return 0;
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement