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