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. // Push
  11. void push(const char *s)
  12. {
  13. strcpy(stack[++top], s);
  14. }
  15.  
  16. // Pop
  17. void pop()
  18. {
  19. top--;
  20. }
  21.  
  22. // Print Stack
  23. void printStack()
  24. {
  25. for (int i = 0; i <= top; i++)
  26. printf("%s", stack[i]);
  27. printf("\n");
  28. }
  29.  
  30. // Reduce with lookahead
  31. int reduce(char lookahead)
  32. {
  33. // F -> id
  34. if (top >= 0 &&
  35. stack[top][0] >= 'a' &&
  36. stack[top][0] <= 'z')
  37. {
  38. pop();
  39. push("F");
  40. return 1;
  41. }
  42.  
  43. // F -> (E)
  44. if (top >= 2 &&
  45. strcmp(stack[top-2], "(") == 0 &&
  46. strcmp(stack[top-1], "E") == 0 &&
  47. strcmp(stack[top], ")") == 0)
  48. {
  49. pop(); pop(); pop();
  50. push("F");
  51. return 1;
  52. }
  53.  
  54. // T -> T * F
  55. if (top >= 2 &&
  56. strcmp(stack[top-2], "T") == 0 &&
  57. strcmp(stack[top-1], "*") == 0 &&
  58. strcmp(stack[top], "F") == 0)
  59. {
  60. pop(); pop(); pop();
  61. push("T");
  62. return 1;
  63. }
  64.  
  65. // T -> F
  66. if (top >= 0 &&
  67. strcmp(stack[top], "F") == 0)
  68. {
  69. pop();
  70. push("T");
  71. return 1;
  72. }
  73.  
  74. // ❗ مهم: E -> E + T (مع check للـ lookahead)
  75. if (top >= 2 &&
  76. strcmp(stack[top-2], "E") == 0 &&
  77. strcmp(stack[top-1], "+") == 0 &&
  78. strcmp(stack[top], "T") == 0)
  79. {
  80. // لو فيه ضرب جاي → متعملش reduce
  81. if (lookahead == '*')
  82. return 0;
  83.  
  84. pop(); pop(); pop();
  85. push("E");
  86. return 1;
  87. }
  88.  
  89. // E -> T
  90. if (top >= 0 &&
  91. strcmp(stack[top], "T") == 0)
  92. {
  93. pop();
  94. push("E");
  95. return 1;
  96. }
  97.  
  98. return 0;
  99. }
  100.  
  101. int main()
  102. {
  103. printf("Enter an Expression:\n");
  104. fgets(input, 100, stdin);
  105.  
  106. while (input[pos])
  107. {
  108. // Ignore spaces
  109. if (isspace(input[pos]))
  110. {
  111. pos++;
  112. continue;
  113. }
  114.  
  115. char temp[2] = {input[pos], '\0'};
  116. push(temp);
  117. pos++;
  118.  
  119. printf("Shift: ");
  120. printStack();
  121.  
  122. // 👇 هنا بقى بنبعت lookahead
  123. while (reduce(input[pos]))
  124. {
  125. printf("Reduce: ");
  126. printStack();
  127. }
  128. }
  129.  
  130. // Final reductions
  131. while (reduce('\0'))
  132. {
  133. printf("Reduce: ");
  134. printStack();
  135. }
  136.  
  137. if (top == 0 && strcmp(stack[0], "E") == 0)
  138. printf("String Accepted\n");
  139. else
  140. printf("String Rejected\n");
  141.  
  142. return 0;
  143. }
Success #stdin #stdout 0s 5320KB
stdin
a  +  b
stdout
Enter an Expression:
Shift: a
Reduce: F
Reduce: T
Reduce: E
Shift: E+
Shift: E+b
Reduce: E+F
Reduce: E+T
Reduce: E
String Accepted