1 # include <stdio.h> 2 # include <string.h> 3 4 //存储LR(0)分析表 5 struct node 6 { 7 char ch; 8 int num; 9 }; 10 struct node table[]={ 11 12 {'s',5},{'t',0},{'t',0},{'s',4},{'t',0},{'t',0},{'t',1},{'t',2},{'t',3}, 13 {'t',0},{'s',6},{'t',0},{'t',0},{'t',0},{'a',0},{'t',0},{'t',0},{'t',0}, 14 {'t',0},{'r',2},{'s',7},{'t',0},{'r',2},{'r',2},{'t',0},{'t',0},{'t',0}, 15 {'t',0},{'r',4},{'r',4},{'t',0},{'r',4},{'r',4},{'t',0},{'t',0},{'t',0}, 16 {'s',5},{'t',0},{'t',0},{'s',4},{'t',0},{'t',0},{'t',8},{'t',2},{'t',3}, 17 {'t',0},{'r',6},{'r',6},{'t',0},{'r',6},{'r',6},{'t',0},{'t',0},{'t',0}, 18 {'s',5},{'t',0},{'t',0},{'s',4},{'t',0},{'t',0},{'t',0},{'t',9},{'t',3}, 19 {'s',5},{'t',0},{'t',0},{'s',4},{'t',0},{'t',0},{'t',0},{'t',0},{'t',10}, 20 {'t',0},{'s',6},{'t',0},{'t',0},{'s',11},{'t',0},{'t',0},{'t',0},{'t',0}, 21 {'t',0},{'r',1},{'s',7},{'t',0},{'r',1},{'r',1},{'t',0},{'t',0},{'t',0}, 22 {'t',0},{'r',3},{'r',3},{'t',0},{'r',3},{'r',3},{'t',0},{'t',0},{'t',0}, 23 {'t',0},{'r',5},{'r',5},{'t',0},{'r',5},{'r',5},{'t',0},{'t',0},{'t',0}, 24 }; 25 26 //符号栈以及状态栈 27 struct node1 28 { 29 int pop; 30 int data[10]; 31 char str[10]; 32 }q1; 33 34 int total=0; //步骤 35 int i; //输入串下标 36 int function(int a,char c,int temp); 37 38 39 int main() 40 { 41 42 char ch[20];//存储输入串 43 44 //栈初始化 45 q1.data[0]=0; 46 q1.pop=1; 47 q1.str[0]='#'; 48 49 i=0; 50 int temp; //下标转换 51 int aaa; //函数返回值,0代表输入串成功分析,1代表出错或者接受 52 53 gets(ch); //输入串; 54 55 // 输出表头和初始化的状态 56 printf("步骤 状态栈 符号栈 输入串 动作 "); 57 printf("%d %d # %s ",++total,q1.data[0],ch); 58 59 60 //循环输出中间过程 61 while(1) 62 { 63 temp=0; 64 //面临不同的输入串采取不同的动作,由函数function实现 65 if(ch[i] == 'i') 66 { 67 temp=q1.data[q1.pop-1]*9+0; 68 aaa=function(0,'i',temp); 69 70 } 71 else if(ch[i] == '+') 72 { 73 temp=q1.data[q1.pop-1]*9+1; 74 aaa=function(1,'+',temp); 75 76 } 77 else if(ch[i] == '*') 78 { 79 temp=q1.data[q1.pop-1]*9+2; 80 aaa=function(2,'*',temp); 81 82 } 83 else if(ch[i] == '(') 84 { 85 temp=q1.data[q1.pop-1]*9+3; 86 aaa=function(3,'(',temp); 87 88 } 89 else if(ch[i] == ')') 90 { 91 temp=q1.data[q1.pop-1]*9+4; 92 aaa=function(4,')',temp); 93 94 } 95 else if(ch[i] == '#') 96 { 97 temp=q1.data[q1.pop-1]*9+5; 98 aaa=function(5,'#',temp); 99 100 } 101 if(aaa==0) 102 break; 103 104 //输出 105 printf("%c%d",table[temp].ch,table[temp].num); 106 printf(" "); 107 q1.str[q1.pop]='