对于给定的文法G[E],消除左递归后的文法是:
E→TE'
E'→+TE'|-TE'|ε
T→FT'
T'→*FT'|/FT'|ε
F→(E)|i
源程序:
#include<stdio.h> char curr; char LL1[1000]; int N=-1; void Top(); void Top1(); void Top2(); void top(); void top1(); void error(); void scaner(); void main() { char ch; int i=0; printf("请输入需要分析的curr语法:(以#结束) "); do{ scanf("%c",&ch); LL1[i] = ch; i++; }while(ch != '#'); scaner(); Top1(); if(curr == '#') printf("成功! "); else{ printf("文法有误!! "); error(); } } void scaner(){ N++; if(LL1[N] == ' '){ N++; }else{ curr = LL1[N]; } } void Top(){ Top2(); top(); } void Top1(){ Top(); top1(); } void Top2(){ if(curr == '('){ scaner(); Top1(); if(curr == ')'){ scaner(); } else { error(); } else { while(1){ if(curr >= 'a' && curr<='z' || curr >= 'A' && curr <= 'Z' || curr >= '0' && curr <= '9'){ scaner(); } else { break; } } } } void top(){ if(curr == '*'){ scaner(); Top2(); Top(); }else if(curr == '/'){ scaner(); Top2(); Top(); }else if(LL1[N+1] == '#' || LL1[N+1] == '+' || LL1[N+1] == '/' || LL1[N+1] == '*' || LL1[N+1] == '-'){ if(LL1[N] != '(' && LL1[N] != ')') error(); } } void top1(){ if(curr == '+'){ scaner(); Top(); top1(); } else if(curr == '-'){ scaner(); Top(); top1(); }else if(LL1[N+1] == '#' || LL1[N+1] == '+' || LL1[N+1] == '/' || LL1[N+1] == '*' || LL1[N+1] == '-'){ if(LL1[N] != '(' && LL1[N] != ')') error(); } } void error(){ printf("%d %c之后的文法有错! ",N,curr); }
运行结果: