fork(1) download
  1.  
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5.  
  6. char stack[100][10];
  7. int top = -1;
  8. int pos = 0;
  9. char input[100];
  10.  
  11.  
  12. void push(const char* s)
  13. {
  14. strcpy(stack[++top], s);
  15. }
  16.  
  17.  
  18. void pop()
  19. {
  20. top--;
  21. }
  22.  
  23.  
  24. void printStack()
  25. {
  26. for (int i = 0; i <= top; i++)
  27. printf("%s", stack[i]);
  28. printf("\n");
  29. }
  30.  
  31. // Reduce
  32. int reduce()
  33. {
  34. if (top != -1 && islower(stack[top][0]))
  35. {
  36. pop();
  37. push("E");
  38. return 1;
  39. }
  40.  
  41.  
  42. if (top >= 2 &&
  43. strcmp(stack[top - 2], "(") == 0 &&
  44. strcmp(stack[top - 1], "E") == 0 &&
  45. strcmp(stack[top], ")") == 0)
  46. {
  47. pop(); pop(); pop();
  48. push("E");
  49. return 1;
  50. }
  51.  
  52.  
  53. if (top >= 2 &&
  54. strcmp(stack[top - 2], "E") == 0 &&
  55. strcmp(stack[top - 1], "*") == 0 &&
  56. strcmp(stack[top], "E") == 0)
  57. {
  58. pop(); pop(); pop();
  59. push("E");
  60. return 1;
  61. }
  62.  
  63.  
  64. if (top >= 2 &&
  65. strcmp(stack[top - 2], "E") == 0 &&
  66. strcmp(stack[top - 1], "+") == 0 &&
  67. strcmp(stack[top], "E") == 0)
  68. {
  69. pop(); pop(); pop();
  70. push("E");
  71. return 1;
  72. }
  73.  
  74. return 0;
  75. }
  76.  
  77. int main()
  78. {
  79.  
  80. fgets(input, sizeof(input), stdin);
  81.  
  82. while (input[pos])
  83. {
  84.  
  85. if (input[pos] == ' ' || input[pos] == '\n')
  86. {
  87. pos++;
  88. continue;
  89. }
  90.  
  91. // SHIFT
  92. char temp[2] = { input[pos], '\0' };
  93. push(temp);
  94. pos++;
  95.  
  96. printf("Shift: ");
  97. printStack();
  98.  
  99. // REDUCE
  100. while (reduce())
  101. {
  102. printf("Reduce: ");
  103. printStack();
  104. }
  105. }
  106.  
  107.  
  108. while (reduce())
  109. {
  110. printf("Reduce: ");
  111. printStack();
  112. }
  113.  
  114.  
  115. if (top == 0 && strcmp(stack[0], "E") == 0)
  116. printf("String Accepted\n");
  117. else
  118. printf("String Rejected\n");
  119.  
  120. return 0;
  121. }
Success #stdin #stdout 0s 5264KB
stdin
a+s*a
stdout
Shift: a
Reduce: E
Shift: E+
Shift: E+s
Reduce: E+E
Reduce: E
Shift: E*
Shift: E*a
Reduce: E*E
Reduce: E
String Accepted