fork download
  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. int top_p = 0;
  5. int top_s = 0;
  6.  
  7. void
  8. push_p(char *s, int c)
  9. {
  10. s[top_p] = c;
  11. top_p++;
  12. }
  13.  
  14. void
  15. push_s(char *s, int c)
  16. {
  17. s[top_s] = c;
  18. top_s++;
  19. }
  20.  
  21. int
  22. pop_p(char *s)
  23. {
  24. top_p--;
  25. return s[top_p];
  26. }
  27.  
  28. int
  29. pop_s(char *s)
  30. {
  31. top_s--;
  32. return s[top_s];
  33. }
  34.  
  35. void
  36. infix_to_postfix(char *in, char *post, char *stk)
  37. {
  38. char operator[256] = {0};
  39.  
  40. operator['('] = 0;
  41. operator['+'] = 1;
  42. operator['-'] = 1;
  43. operator['*'] = 2;
  44. operator['/'] = 2;
  45. while (*in) {
  46. if (isdigit(*in)) {
  47. push_p(post, *in);
  48. } else { /* Operator */
  49. while (1) {
  50. switch (*in) {
  51. case '(':
  52. push_s(stk, *in);
  53. break;
  54. case ')':
  55. while (stk[top_s - 1] != '(') {
  56. push_p(post, pop_s(stk));
  57. }
  58. pop_s(stk);
  59. break;
  60. default:
  61. break;
  62. }
  63. if (*in == '(' && *in == ')') {
  64. break;
  65. }
  66. /* go here */
  67. if (!stk[top_s - 1]) {
  68. while (operator[stk[top_s - 1]] >= operator[*in]) {
  69. push_p(post, pop_s(stk));
  70. if (stk[top_s - 1]) {
  71. break;
  72. }
  73. }
  74. }
  75. break;
  76. }
  77. if (*in != '(' && *in != ')') {
  78. push_s(stk, *in);
  79. }
  80. }
  81. in++;
  82. }
  83. }
  84.  
  85. void
  86. stack_empty(char *post, char *stk)
  87. {
  88. while (stk[top_s - 1]) {
  89. push_p(post, pop_s(stk));
  90. }
  91. }
  92.  
  93. int
  94. main(int argc, char **argv)
  95. {
  96. char infix[] = "2*((3-5)*2)";
  97. char postfix[256] = {0};
  98. char stack[256] = {0};
  99.  
  100. infix_to_postfix(infix, postfix, stack);
  101. stack_empty(postfix, stack);
  102. printf("%s\n", postfix);
  103. return 0;
  104. }
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
235-2**