![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <stack> 5 #include <queue> 6 #include <map> 7 #include <algorithm> 8 #include <vector> 9 10 using namespace std; 11 12 char action[10][3][5]= {{"S3#","S4#","NUll"}, 13 {"NUll","NUll","acc"}, 14 {"S6#","S7#","NUll"}, 15 {"S3#","S4#","NUll"}, 16 {"r3#","r3#","NUll"}, 17 {"NUll","NUll","r1#"}, 18 {"S6#","S7#","NUll"}, 19 {"NUll","NUll","r3#"}, 20 {"r2#","r2#","NUll"}, 21 {"NUll","NUll","r2#"} 22 }; 23 /* GOTO表*/ 24 int goto1[10][2]= {1,2, 25 0,0, 26 0,5, 27 0,8, 28 0,0, 29 0,0, 30 0,9, 31 0,0, 32 0,0, 33 0,0 34 }; 35 char vt[3]= {'a','b','#'}; /*存放终结符*/ 36 char vn[2]= {'S','B'}; /*存放非终结符*/ 37 char *LR[5]= {"E->S#","S->BB#","B->aB#","B->b#"}; /*存放产生式*/ 38 /*输出状态栈、输出符号栈、输出输入串*/ 39 40 int main() 41 { 42 // printf("%s " ,action[0][1]); 43 int y,z,m,n,top,top1,top2,top3,j,k,i,g,h,l,p; 44 char x; 45 char b[10];//符号栈 46 char str[10];//输入串 47 int a[10];//状态栈 48 char copy1[20],copy[20]; 49 int count = 0; 50 top = top1 = top2 = top3 = 0; 51 memset(a,0,sizeof(a)); 52 a[top1]=0; 53 54 b[top2] = '#'; 55 56 scanf("%s",str); 57 z=0; 58 top3 = strlen(str); 59 int flag = 0; 60 do 61 { 62 y=z; 63 //if() break; 64 m=0; 65 n=0; /*y,z指向状态栈栈顶*/ 66 g=top; 67 j=0; 68 k=0; 69 x=str[top]; 70 count++; 71 printf("%d ",count); 72 while(m<=top1) /*输出状态栈*/ 73 { 74 printf("%d",a[m]); 75 m=m+1; 76 } 77 printf(" "); 78 while(n<=top2) /*输出符号栈*/ 79 { 80 printf("%c",b[n]); 81 n=n+1; 82 } 83 printf(" "); 84 while(g<top3) /*输出输入串*/ 85 { 86 printf("%c",str[g]); 87 g=g+1; 88 } 89 printf(" "); 90 91 92 93 /*查动作表*/ 94 if(x == 'a')j=0; 95 if(x == 'b')j=1; 96 if(x == '#')j=2; 97 if(action[y][j]=="NUll"){ 98 printf("error "); 99 return 0; 100 } 101 102 strcpy(copy,action[y][j]); 103 104 /*处理移进*/ 105 if(copy[0]=='S') 106 { 107 z=copy[1]-'0'; 108 top1=top1+1; 109 top2=top2+1; 110 a[top1]=z; 111 b[top2]=x; 112 top=top+1; 113 i=0; 114 while(copy[i]!='#') 115 { 116 printf("%c",copy[i]); 117 i++; 118 } 119 printf(" "); 120 } 121 122 /*处理归约*/ 123 if(copy[0]=='r') 124 { 125 i=0; 126 while(copy[i]!='#') 127 { 128 printf("%c",copy[i]); 129 i++; 130 } 131 h=copy[1]-'0'; 132 strcpy(copy1,LR[h]); 133 if(copy1[0]=='S')k=0; 134 if(copy1[0]=='B')k=1; 135 l=strlen(LR[h])-4; 136 top1=top1-l+1; 137 top2=top2-l+1; 138 y=a[top1-1]; 139 p=goto1[y][k]; 140 a[top1]=p; 141 b[top2]=copy1[0]; 142 z=p; 143 printf(" "); 144 printf("%d ",p); 145 } 146 if(copy[0]=='a') { printf("%s ",copy); flag =1;} 147 148 if(copy[0]=='N') {printf("error ");flag = 1;} 149 if(flag) break; 150 }while(1); 151 return 0; 152 }