fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. char stack[50], input[50];
  5. int top = -1, i = 0;
  6.  
  7. void push(char c) {
  8. stack[++top] = c;
  9. stack[top+1] = '\0';
  10. }
  11.  
  12. int try_reduce() {
  13. if (stack[top] == '2') {
  14. stack[top] = 'S';
  15. printf("Reduce: S->2\tStack: %s\n", stack);
  16. return 1;
  17. }
  18.  
  19. if (top >= 2 && stack[top]=='0' && stack[top-1]=='S' && stack[top-2]=='0') {
  20. top -= 2;
  21. stack[top] = 'S';
  22. printf("Reduce: S->0S0\tStack: %s\n", stack);
  23. return 1;
  24. }
  25.  
  26. if (top >= 2 && stack[top]=='1' && stack[top-1]=='S' && stack[top-2]=='1') {
  27. top -= 2;
  28. stack[top] = 'S';
  29. printf("Reduce: S->1S1\tStack: %s\n", stack);
  30. return 1;
  31. }
  32.  
  33. return 0;
  34. }
  35.  
  36. int main() {
  37. strcpy(input, "10201$");
  38.  
  39. printf("Stack\tInput\tAction\n");
  40.  
  41. while (input[i] != '\0') {
  42. push(input[i]);
  43. printf("%s\t%s\tShift %c\n", stack, input+i+1, input[i]);
  44.  
  45. while (try_reduce());
  46.  
  47. i++;
  48. }
  49.  
  50. if (strcmp(stack, "S$") == 0)
  51. printf("String Accepted\n");
  52. else
  53. printf("String Rejected\n");
  54.  
  55. return 0;
  56. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Stack	Input	Action
1	0201$	Shift 1
10	201$	Shift 0
102	01$	Shift 2
Reduce: S->2	Stack: 10S
10S0	1$	Shift 0
Reduce: S->0S0	Stack: 1SS0
1S1	$	Shift 1
Reduce: S->1S1	Stack: SS1
S$		Shift $
String Accepted