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 cursor = 0;
  8. char buffer[100];
  9.  
  10. void push(const char *symbol) {
  11. strcpy(stack[++top], symbol);
  12. }
  13.  
  14. void pop() {
  15. if (top >= 0) top--;
  16. }
  17.  
  18. void show_stack() {
  19. for (int i = 0; i <= top; i++) {
  20. printf("%s", stack[i]);
  21. }
  22. printf("\n");
  23. }
  24.  
  25. int try_reduce() {
  26. if (top >= 2 && strcmp(stack[top - 2], "(") == 0 && strcmp(stack[top - 1], "E") == 0 && strcmp(stack[top], ")") == 0) {
  27. pop(); pop(); pop();
  28. push("E");
  29. return 1;
  30. }
  31.  
  32. if (top >= 2 && strcmp(stack[top - 2], "E") == 0 && (strcmp(stack[top - 1], "+") == 0 || strcmp(stack[top - 1], "*") == 0) && strcmp(stack[top], "E") == 0) {
  33. pop(); pop(); pop();
  34. push("E");
  35. return 1;
  36. }
  37.  
  38. if (top != -1 && islower(stack[top][0]) && strlen(stack[top]) == 1) {
  39. pop();
  40. push("E");
  41. return 1;
  42. }
  43.  
  44. return 0;
  45. }
  46.  
  47. int main() {
  48. printf("Enter an Expression: ");
  49. fgets(buffer, sizeof(buffer), stdin);
  50. buffer[strcspn(buffer, "\n")] = 0;
  51.  
  52. while (buffer[cursor] != '\0') {
  53. if (isspace(buffer[cursor])) {
  54. cursor++;
  55. continue;
  56. }
  57.  
  58. char current[2] = {buffer[cursor], '\0'};
  59. push(current);
  60. cursor++;
  61.  
  62. printf("Shift: ");
  63. show_stack();
  64.  
  65. while (try_reduce()) {
  66. printf("Reduce: ");
  67. show_stack();
  68. }
  69. }
  70.  
  71. if (top == 0 && strcmp(stack[0], "E") == 0) {
  72. printf("String Accepted\n");
  73. } else {
  74. printf("String Rejected\n");
  75. }
  76.  
  77. return 0;
  78. }
Success #stdin #stdout 0s 5320KB
stdin
(a          + (b*a))
stdout
Enter an Expression: 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