好久没管自己的博客了,今天写了点。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char row[20]={0};
char col[20]={0};
char table[20][20][5]={0};
char stack[20];
char buffer[20];
int index=0;
int sTop=0;
int getRowIndex(char ch);
int getColIndex(char ch);
void outputTable();
void outputRow();
void outputCol();
void init()
{
//
strcpy(row,"a^(),{1}quot;);
strcpy(col,"STR");
strcpy(table[0][0],"a");
strcpy(table[0][1],"^");
strcpy(table[0][2],"(T)");
strcpy(table[1][0],"SR");
strcpy(table[1][1],"SR");
strcpy(table[1][2],"SR");
strcpy(table[2][3],"@");// @ 表示空
strcpy(table[2][4],",SR");
}
void outputTable()
{
int rowlen=strlen(row);
int collen=strlen(col);
for (int i=0;i<collen;i++)
{
for (int j=0;j<rowlen;j++)
{
if (table[i][j][0]=='\0')
{
printf("---\t");
}
else
{
printf("%c->%s\t",col[i],table[i][j]);
}
}
printf("\n");
}
}
void outputRow()
{
int rowlen=strlen(row);
for (int i=0;i<rowlen;i++)
{
printf("%c\t",row[i]);
}
printf("\n");
}
void outputCol()
{
int collen=strlen(col);
for (int i=0;i<collen;i++)
{
printf("%c\t",col[i]);
}
printf("\n");
}
int getRowIndex(char ch)
{
int rowlen=strlen(row);
for (int i=0;i<rowlen;i++)
{
if (row[i]==ch)
{
return i;
}
}
return -1;
}
int getColIndex(char ch)
{
int collen=strlen(col);
for (int i=0;i<collen;i++)
{
if (col[i]==ch)
{
return i;
}
}
return -1;
}
bool AnalyzeMachine()
{
stack[sTop++]='
;stack[sTop++]='S';char a=buffer[index++];char x;char rule[5];start:sTop--;x=stack[sTop];if (-1!=getRowIndex(x))//属于非终结{if (x==a){a=buffer[index++];goto start;}elsereturn false;}else{if (x=='
){if (x==a)return true;elsereturn false;}else{strcpy(rule,table[getColIndex(x)][getRowIndex(a)]);if (rule[0]=='\0'){return false;}else{if (rule[0]!='@'){int len=strlen(rule);while (len!=0){stack[sTop++]=rule[--len];}goto start;}}}}}void main(){init();outputTable();outputRow();outputCol();// printf("%s\n",table[getRowIndex('(')][getColIndex('T')]);// printf("%c->%s\n",col[getColIndex('T')],table[getColIndex('T')][getRowIndex('(')]);// printf("%d\n",getRowIndex('('));// printf("%d\n",getColIndex('T'));// printf("%s\n",table[1][2]);strcpy(buffer,"(a,a,^){1}quot;);if(AnalyzeMachine()){printf("Success\n");}else{printf("Failing\n");}}