Advertisement
ruhul0

Infix to Postfix

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