用C语言写一个消除文法左递归的程序
时间: 2023-11-18 19:05:38 浏览: 163
以下是一个消除文法左递归的C语言程序:
```c
#include <stdio.h>
#include <string.h>
#define MAX_PROD 10
#define MAX_LEN 10
int n;
char non_term[MAX_PROD];
char prod[MAX_PROD][MAX_LEN];
char new_prod[MAX_PROD][MAX_LEN];
void eliminate_left_recursion(int i) {
int j, k, l, m;
char new_non_term = non_term[i];
int count = 0;
for (j = 0; j < i; j++) {
if (non_term[j] == new_non_term) {
count++;
}
}
for (j = 0; j < i; j++) {
if (non_term[j] != new_non_term) {
strcpy(new_prod[j], prod[j]);
for (k = 0; k < count; k++) {
strcat(new_prod[j], "'");
}
strcat(new_prod[j], " ");
strcat(new_prod[j], new_non_term);
}
}
for (j = 0; j < i; j++) {
if (non_term[j] == new_non_term) {
strcpy(new_prod[j + i], prod[j]);
for (k = 0; k < count; k++) {
strcat(new_prod[j + i], "'");
}
for (l = 0; l < i; l++) {
if (non_term[l] != new_non_term) {
strcat(new_prod[j + i], " ");
strcat(new_prod[j + i], non_term[l]);
}
}
strcat(new_prod[j + i], "'");
}
}
strcpy(non_term, new_non_term);
for (j = 0; j < i; j++) {
strcpy(prod[j], new_prod[j]);
}
n += count;
}
int main() {
int i, j;
printf("Enter number of productions: ");
scanf("%d", &n);
printf("Enter productions:\n");
for (i = 0; i < n; i++) {
scanf("%s", prod[i]);
non_term[i] = prod[i][0];
}
for (i = 0; i < n; i++) {
for (j = 0; j < i; j++) {
if (non_term[i] == non_term[j]) {
eliminate_left_recursion(i);
i--;
break;
}
}
}
printf("Productions after eliminating left recursion:\n");
for (i = 0; i < n; i++) {
printf("%s\n", prod[i]);
}
return 0;
}
```
该程序首先读取输入的产生式,并检查是否存在左递归。如果找到了左递归,它将使用新的非终结符替换左递归,并生成新的产生式。然后,它将使用新的非终结符和产生式替换原始的非终结符和产生式。最后,它输出消除左递归后的产生式。
阅读全文