fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. #define SIZE 50
  5. int top=-1;
  6. int top_post = -1;
  7. void push(char symbol);
  8. char pop();
  9. char stack[SIZE],infix[SIZE],post[SIZE],a;
  10. int precedence(char symbol)
  11. {
  12. switch (symbol)
  13. {
  14. case '+':
  15. case '-':
  16. return 1;
  17.  
  18. case '*':
  19. case '/':
  20. return 2;
  21.  
  22. case '^':
  23. return 3;
  24. default:
  25. return -1;
  26. }
  27. }
  28. int highest_precedence()
  29. {
  30. int high = 0;
  31. for (int i = top; i >= 0; i--)
  32. {
  33. char symbol = stack[i];
  34. if (symbol == '(')
  35. break;
  36. int now = precedence(symbol);
  37.  
  38. if (now != -1)
  39. {
  40.  
  41. if (now > high)
  42. {
  43. high = now;
  44. }
  45. }
  46. }
  47. return high;
  48. }
  49.  
  50. void push(char symbol)
  51. {
  52. if(top>=SIZE-1)
  53. {
  54. printf("overflow");
  55. exit(1);
  56. }
  57. else
  58. {
  59. top++;
  60. stack[top]=symbol;
  61. }
  62. }
  63. char pop()
  64. {
  65. if (top<0)
  66. printf("underflow\n");
  67. else
  68. {
  69. top--;
  70. return stack[top+1];
  71. }
  72. }
  73. void append(char symbol)
  74. {
  75. if(top>=SIZE-1)
  76. {
  77. printf("overflow\n");
  78. exit(1);
  79. }
  80. else
  81. {
  82. top_post++;
  83. post[top_post]=symbol;
  84. }
  85. }
  86. int main()
  87. {
  88. char del;
  89. gets(infix);
  90. int len=strlen(infix);
  91.  
  92. for (int i=0;i<len;i++)
  93. {
  94. char symbol=infix[i];
  95. switch (symbol)
  96. {
  97. case '+':
  98. case '-':
  99. case '*':
  100. case '/':
  101. case '^':
  102. if (top != -1 && highest_precedence()>=precedence(symbol))// checks if the current symbol being scanned has the highest precedence
  103. {
  104. append(pop());// prints to postfix
  105. }
  106. push(symbol);// pushes to stack
  107. break;
  108. case '(':
  109. push(symbol);
  110. break;
  111. case ')':
  112. while((del = pop()) != '(') //pops all elements and prints them until '(' is encountered.
  113. append(del);
  114. break;
  115. default:
  116. append(symbol);
  117. }
  118. }
  119. while(top!=-1)
  120. append(pop());
  121. append('\0');
  122. for(int i=0;i<top_post;i++)
  123. {
  124. printf("%c ",post[i]);
  125. }
  126. printf("\n");
  127. return 0;
  128. }
Success #stdin #stdout 0s 5400KB
stdin
Standard input is empty
stdout