使用递归的方法计算 lastvt集合
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
#define LENGTH 5 //产生式的长度
#define COUNT 7 //产生式的个数
//产生式
/*
char product[][LENGTH]={
{'S','a'},
{'S','^'},
{'S','(','T',')'},
{'T','T',',','S'},
{'T','S'},
};//课本P122第1题
*/
char product[][LENGTH]={
{'S','V'},
{'V','T'},
{'V','V','i','T'},
{'T','F'},
{'T','T','+','F'},
{'F',')','V','*'},
{'F','('},
};//课本P122第3题
void outputProduct()//打印产生式
{
int i=0,j=0;
while (product[i][0]!=NULL)//产生式左边不空
{
printf("/n %c ->",product[i][0]);//打印非终结符
j=1;
while(product[i][j]!=NULL)
{
printf(" %c ",product[i][j]);//打印终结符
j++;
}
i++;//下一条产生式
}
}
char lastTerm(char *s)//最后一个终结符。若没有,返回非终结符
{
int i=1;//从第二个开始,因为存储的是全部产生式
char last=s[i];//最后一个终结符,初始值为产生式右边的第一个符号
while (s[i]!=NULL)
{
if (s[i]<'A' || s[i]>'Z')//是终结符
{
last=s[i];//记住
}
i++;
}
return last;//返回产生式右边的第一个符号
}
void lastVT(char s)//计算单个非终结符的lastVT集合,直接打印
{
for (int i=0;i<COUNT;i++)
{
if (product[i][0]==s)
{
while (product[i][0]==s)
{
if (lastTerm(product[i])<'A' || lastTerm(product[i])>'Z')//终结符
{
printf("%c ",lastTerm(product[i]));
}
else
{
lastVT(lastTerm(product[i]));
}
i++;//下一个产生式
}
}
}
}
void outputLastVT()//打印所有非终结符的firstVT集合
{
for (int i=0;i<COUNT;i++)
{
printf("/nlastVT(%c)= ",product[i][0]);
while(product[i][0]==product[i+1][0])
{
i++;
}
lastVT(product[i][0]);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
outputProduct();
outputLastVT();
printf("/n");
system("pause");
return 0;
}
l