制度下降算法c语言

复制代码
#include<stdio.h>
#include<string.h>
int location=0;			//遍历字符串的当前位置
char arr[20]="id+id*id#";
void error();		//错误提示函数
/*
每一个非终结符都构造一个函数
*/
void E(char t);			
void Ep(char t);
void T(char t);
void Tp(char t);
void F(char t);

void E(char t){
    if(t=='('){
        printf("E->TE'");
        printf("\n");
        T(arr[location]);
        Ep(arr[location]);
    }else if(t=='i'){
        printf("E->TE'");
        printf("\n");
        T(arr[location]);
        Ep(arr[location]);
    }
    else{
        error();
        location++;
        E(arr[location]);
    }
}
void T(char t){
    if(t=='i'){
        printf("T->FT'");
        printf("\n");
        F(arr[location]);
        Tp(arr[location]);
    }else if(t=='('){
        printf("T->FT'");
        printf("\n");
        F(arr[location]);
        Tp(arr[location]);
    }else{
        error();
        location++;
        T(arr[location]);
    }
}
void Ep(char t){
    if(t=='+'){
        printf("E'->+TE'");
        printf("\n");
        location++;
        T(arr[location]);
        Ep(arr[location]);
    }else if(t==')'){
        printf("E'->&");
        printf("\n");
    }else if(t=='#'){
    }
    else{
        error();
        if(t=='i')
            location+=2;
        else
            location++;
        Ep(arr[location]);
    }
}
void Tp(char t){
    switch(t){
    case '+':
        printf("T'->&");
        printf("\n");
        break;
    case '*':
        printf("T'->*FT'");
        printf("\n");
        location++;
        F(arr[location]);
        Tp(arr[location]);
        break;
    case ')':
        printf("T'->&");
        printf("\n");
        break;
    case '#':
        printf("T'->&");
        printf("\n");
        break;
    default:
        error();
        if(t=='i')
            location+=2;
        else
            location++;
        Tp(arr[location]);
        break;
    }
}
void F(char t){
    if(t=='i'){
        printf("F->id");
        printf("\n");
        location+=2;
    }else if(t=='('){
        printf("F->(E)");
        printf("\n");
    }else{
        error();
        location++;
        F(arr[location]);
    }
}
void error(){
    printf("有一个错误,略过当前词法记号");
    printf("\n");
}
int main(){
    E(arr[location]);
}

运行结果:

相关推荐
WJSKad123525 分钟前
【DepthPro】实战教程:单目深度估计算法详解与应用
算法
wzqllwy27 分钟前
8 大经典排序算法(Java 实现):原理 + Demo + 核心分析
java·算法·排序算法
We་ct28 分钟前
LeetCode 77. 组合:DFS回溯+剪枝,高效求解组合问题
开发语言·前端·算法·leetcode·typescript·深度优先·剪枝
重生之我是Java开发战士32 分钟前
【递归、搜索与回溯】二叉树中的深度优先搜索:布尔二叉树,求根节点到叶节点数字之和,二叉树剪枝,验证二叉搜索树,第K小的元素,二叉树的所有路径
算法·深度优先·剪枝
篮l球场32 分钟前
矩阵置零
算法
lihihi34 分钟前
P1650 [ICPC 2004 Shanghai R] 田忌赛马(同洛谷2587)
开发语言·算法·r语言
朱一头zcy34 分钟前
[牛客]BC38 变种水仙花
算法
努力学算法的蒟蒻34 分钟前
day105(3.6)——leetcode面试经典150
算法·leetcode·面试
猫猫的小茶馆36 分钟前
【Linux 驱动开发】Linux 内核启动过程详解
linux·c语言·arm开发·驱动开发·stm32·单片机·mcu
Chan1637 分钟前
LeetCode 热题 100 | 矩阵
java·开发语言·数据结构·算法·spring·java-ee·intellij-idea