1、M 0 T M |T F | NN 1 F N |F i | ( E )2.LL(1)分析表表1.LL(1)分析表i+-*/()#EMT,pMMT,n,pTNF,pNNF,nF,n)E,nOK二、数据结构1.输入表达式定义char型数组expstr为存放输入表达式的数组,char expstr100;2.分析栈定义一个栈来进行LL(1)分析。栈中有bottom、top、stacksize等元素,用于程序调用栈和对栈操作。typedef struct /定义语法的栈 SElemType *bottom;/底 SElemType *top;/顶 int stacksize;SqStack; (包括
2、:概要设计、数据结构、流程图、关键函数等有选择填写)源程序代码:(加入注释)#includestdio.hcstdlibusing namespace std;#define STACKSIZE 30 /栈大小#define STACKINCREMENT 10 /栈增量#define OK 1#define Error 0#define OVERFLOW -1typedef char SElemType;typedef int Status;int i=0;int count1=0;int count2=0; /计数终结符的个数Status InitStack(SqStack &S) /初始化
3、栈 S.bottom=(SElemType*)malloc(STACKSIZE*sizeof(SElemType); if(!S.bottom) exit(OVERFLOW); S.top=S.bottom; S.stacksize=STACKSIZE; return OK;Status PUSH(SqStack &S,SElemType e) if(S.top-S.bottom=S.stacksize) S.bottom=(SElemType*)realloc(S.bottom,(S.stacksize+STACKINCREMENT)*sizeof(SElemType); S.top=S.b
4、ottom+S.stacksize; S.stacksize+=STACKINCREMENT; *(S.top)=e; (S.top)+;Status POP(SqStack &S,SElemType &e) if(S.top=S.bottom) return Error; S.top-; e=*(S.top);void wrong()/调用此函数,表示出错 cout=0&sncsi i+; while(si count1+; while(count1!=0) i-; count1-; /是字母或数字返回1 /不是字母或数字返回0void LL1(SqStack &S,char s,int i
5、)/LL1文法分析函数 SElemType e; PUSH(S,); while(si! if(ch_judge(s,i) POP(S,e);(ter_judge(e) /是非终结符 if(e=si= break; /表达式正确 else if(e=si! wrong(); else if(e!) /分析表匹配 switch(e) case : if(num_letter(s,i)|si= e=M; / E M PUSH(S,e); if(si=|si= e=si; else if(si=N /T N if(num_letter(s,i) /将连续的终结符压栈 count2+; /给连续终结符
6、计数 /使si为连续终结符即一个整数的最后一字 default:)/如果是数字或字母则依次计数 while(ter_judge(e) if(e=si) while(count2! count2-; else /如果是+-*/则直接比较int main() SqStack S; InitStack(S);LL(1)nPlease enter the expression and end with the # cinexpstr; LL1(S,expstr,i);Right! 程序运行结果:(截屏)图1.正确的算术表达式(a+b)*(c/B)的判断图2.错误的算术表达式a/b+的判断思考问题回答:(如果有)LL(1)分析法和递归下降子程序法在语法分析中同属于自顶向下分析法,LL(1)分析法相对于递归下降子程序法的优势是:LL(1)分析法消除了文法的左递归性,而且克服了回溯,使程序运行的效率大大提升。
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1