fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4.  
  5. char stack[100][10];
  6. int top = -1;
  7. int idx = 0;
  8. char input[100];
  9.  
  10. void push(const char *s) {
  11. strcpy(stack[++top], s);
  12. }
  13.  
  14. void pop() {
  15. top--;
  16. }
  17.  
  18. void printStack() {
  19. for (int i = 0; i <= top; i++) printf("%s", stack[i]);
  20. printf("\n");
  21. }
  22.  
  23. int reduce() {
  24. if (top >= 2 &&
  25. strcmp(stack[top-2], "E") == 0 &&
  26. strcmp(stack[top-1], "+") == 0 &&
  27. strcmp(stack[top], "E") == 0) {
  28. pop(); pop(); pop();
  29. push("E");
  30. return 1;
  31. }
  32.  
  33. if (top!=-1 && stack[top][0]>='a'&&stack[top][0]<='z')
  34. {
  35. pop();
  36. push("E");
  37. return 1;
  38. }
  39.  
  40. if (top >= 2 &&
  41. strcmp(stack[top-2], "E") == 0 &&
  42. strcmp(stack[top-1], "*") == 0 &&
  43. strcmp(stack[top], "E") == 0) {
  44. pop(); pop(); pop();
  45. push("E");
  46. return 1;
  47. }
  48.  
  49. if (top >= 2 &&
  50. strcmp(stack[top-2], "(") == 0 &&
  51. strcmp(stack[top-1], "E") == 0 &&
  52. strcmp(stack[top], ")") == 0) {
  53. pop(); pop(); pop();
  54. push("E");
  55. return 1;
  56. }
  57.  
  58. return 0;
  59. }
  60.  
  61. int main() {
  62. fgets(input, sizeof(input), stdin);
  63.  
  64. while (input[idx]) {
  65. if (isspace(input[idx])) {
  66. idx++;
  67. continue;
  68. }
  69.  
  70. char temp[2] = {input[idx], '\0'};
  71. push(temp);
  72. idx++;
  73.  
  74. printf("Shift: ");
  75. printStack();
  76.  
  77. while (reduce()) {
  78. printf("Reduce: ");
  79. printStack();
  80. }
  81. }
  82.  
  83. if (top == 0 && strcmp(stack[0], "E") == 0)
  84. printf("String Accepted\n");
  85. else
  86. printf("String Rejected\n");
  87.  
  88. return 0;
  89. }
Success #stdin #stdout 0s 5324KB
stdin
( a + (b*a))
stdout
Shift: (
Shift: (a
Reduce: (E
Shift: (E+
Shift: (E+(
Shift: (E+(b
Reduce: (E+(E
Shift: (E+(E*
Shift: (E+(E*a
Reduce: (E+(E*E
Reduce: (E+(E
Shift: (E+(E)
Reduce: (E+E
Reduce: (E
Shift: (E)
Reduce: E
String Accepted