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