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 pos = 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++)
  20. printf("%s", stack[i]);
  21. printf("\n");
  22. }
  23.  
  24. int reduce(char lookahead) {
  25.  
  26. // F -> id
  27. if (top >= 0 &&
  28. stack[top][0] >= 'a' &&
  29. stack[top][0] <= 'z')
  30. {
  31. pop();
  32. push("F");
  33. return 1;
  34. }
  35.  
  36. // F -> (E)
  37. if (top >= 2 &&
  38. strcmp(stack[top-2], "(") == 0 &&
  39. strcmp(stack[top-1], "E") == 0 &&
  40. strcmp(stack[top], ")") == 0)
  41. {
  42. pop(); pop(); pop();
  43. push("F");
  44. return 1;
  45. }
  46.  
  47. // T -> T * F
  48. if (top >= 2 &&
  49. strcmp(stack[top-2], "T") == 0 &&
  50. strcmp(stack[top-1], "*") == 0 &&
  51. strcmp(stack[top], "F") == 0)
  52. {
  53. pop(); pop(); pop();
  54. push("T");
  55. return 1;
  56. }
  57.  
  58. // T -> F
  59. if (top >= 0 && strcmp(stack[top], "F") == 0)
  60. {
  61. pop();
  62. push("T");
  63. return 1;
  64. }
  65.  
  66. // E -> E + T (مع مراعاة precedence)
  67. if (top >= 2 &&
  68. strcmp(stack[top-2], "E") == 0 &&
  69. strcmp(stack[top-1], "+") == 0 &&
  70. strcmp(stack[top], "T") == 0)
  71. {
  72. // لو الجاي * نستنى
  73. if (lookahead == '*')
  74. return 0;
  75.  
  76. pop(); pop(); pop();
  77. push("E");
  78. return 1;
  79. }
  80.  
  81. // E -> T (مع مراعاة precedence)
  82. if (top >= 0 && strcmp(stack[top], "T") == 0)
  83. {
  84. // لو الجاي * يبقى لسه هنكوّن T * F
  85. if (lookahead == '*')
  86. return 0;
  87.  
  88. pop();
  89. push("E");
  90. return 1;
  91. }
  92.  
  93. return 0;
  94. }
  95.  
  96. int main() {
  97. printf("Enter an Expression:\n");
  98. fgets(input, 100, stdin);
  99.  
  100. while (input[pos]) {
  101.  
  102. if (isspace(input[pos])) {
  103. pos++;
  104. continue;
  105. }
  106.  
  107. char temp[2] = {input[pos], '\0'};
  108. push(temp);
  109. pos++;
  110.  
  111. printf("Shift: ");
  112. printStack();
  113.  
  114. while (reduce(input[pos])) {
  115. printf("Reduce: ");
  116. printStack();
  117. }
  118. }
  119.  
  120. while (reduce('\0')) {
  121. printf("Reduce: ");
  122. printStack();
  123. }
  124.  
  125. if (top == 0 && strcmp(stack[0], "E") == 0)
  126. printf("String Accepted\n");
  127. else
  128. printf("String Rejected\n");
  129.  
  130. return 0;
  131. }
Success #stdin #stdout 0s 5324KB
stdin
h*j +(k)
stdout
Enter an Expression:
Shift: h
Reduce: F
Reduce: T
Shift: T*
Shift: T*j
Reduce: T*F
Reduce: T
Reduce: E
Shift: E+
Shift: E+(
Shift: E+(k
Reduce: E+(F
Reduce: E+(T
Reduce: E+(E
Shift: E+(E)
Reduce: E+F
Reduce: E+T
Reduce: E
String Accepted