fork download
  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. char postfix[64] = {0};
  5. char stack[64] = {0};
  6. int top_p = 0;
  7. int top_s = 0;
  8.  
  9. void
  10. push_s(char d)
  11. {
  12. stack[top_s] = d;
  13. top_s++;
  14. }
  15.  
  16. void
  17. push_p(char d)
  18. {
  19. postfix[top_p] = d;
  20. top_p++;
  21. }
  22.  
  23. int
  24. _pop_s(void)
  25. {
  26. top_s--;
  27. return stack[top_s];
  28. }
  29.  
  30. void
  31. stack_init(void)
  32. {
  33. stack[top_s] = 0x00;
  34. }
  35.  
  36. int
  37. pop_s(void)
  38. {
  39. char d;
  40. d = _pop_s();
  41. stack_init();
  42. return d;
  43. }
  44.  
  45. int
  46. _pop_p()
  47. {
  48. top_p--;
  49. return postfix[top_p];
  50. }
  51.  
  52. void
  53. postfix_init(void)
  54. {
  55. postfix[top_p] = 0x00;
  56. }
  57.  
  58. int
  59. pop_p(void)
  60. {
  61. char d;
  62. d = _pop_p();
  63. postfix_init();
  64. return d;
  65. }
  66.  
  67. void
  68. infix_to_postfix(char *in)
  69. {
  70. char operator[256] = {0};
  71.  
  72. operator['('] = 0;
  73. operator['+'] = 1;
  74. operator['-'] = 1;
  75. operator['*'] = 2;
  76. operator['/'] = 2;
  77. while (*in) {
  78. if (isdigit(*in)) {
  79. push_p(*in);
  80. } else { /* operator */
  81. while (1) {
  82. switch (*in) {
  83. case '(':
  84. push_s(*in);
  85. break;
  86. case ')':
  87. while (stack[top_s -1] != '(') {
  88. push_p(pop_s());
  89. }
  90. pop_s();
  91. break;
  92. default:
  93. break;
  94. }
  95. if (*in == '(' || *in == ')') {
  96. break;
  97. }
  98. if (!stack[top_s]) {
  99. while (operator[stack[top_s - 1]] >= operator[*in]) {
  100. push_p(pop_s());
  101. if (stack[top_s - 1]) {
  102. break;
  103. }
  104. }
  105. }
  106. break;
  107. }
  108. if (*in != '(' || *in != ')') {
  109. push_s(*in);
  110. }
  111. }
  112. in++;
  113. }
  114. }
  115.  
  116. void
  117. stack_empty()
  118. {
  119. while (stack[top_s - 1]) {
  120. push_p(pop_s());
  121. }
  122. }
  123.  
  124. int
  125. main(int argc, char **argv)
  126. {
  127. char infix[] = "1+2-3*4/3";
  128.  
  129. infix_to_postfix(infix);
  130. stack_empty();
  131. printf("%s\n", postfix);
  132. return 0;
  133. }
  134.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
12+34*3/-