数据结构设计——魔王语言

【问题描述】

有一个魔王总是使用自己的一种非常精练而抽象的语言讲话,没有人能听得懂,但他的语言是可以逐步解释成人能听懂的语言,因为他的语言是由以下两种形式的规则由人的语言逐步抽象上去的:

在这两种形式中,从左到右均表示解释。试写一个魔王语言的解释系统,把他的话解释成人能听得懂的话。

【基本要求】

用下述两条具体规则和上述规则形式(2)实现。设大写字母表示魔王语言的词汇;小写字母表示人的语言词汇;希腊字母表示可以用大写字母或小写字母代换的变量。魔王语言可含人的词汇。

【测试数据】

B(ehnxgz)B解释成tsaedsaeezegexenehetsaedsae

有点简单,不想好好做,最后的B A 的替换就省略了:

扫描二维码关注公众号,回复: 8668315 查看本文章

思路就是用栈,队列实现

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char say[100];
typedef struct SqStack{
    char data[100];
    int top,bottom;
}SqStack,SqQueue;
void ruZhan(SqStack *S,char c){
    if(S->top == 100 - 1){
        printf("栈满!\n");
    }else{
        S->top++;
        S->data[S->top] = c;
    }
}
char chuZhan(SqStack *S){
    if(S->top == 0){
        printf("栈空!\n");
        return -1;
    }else{
        char e;
        e = S->data[S->top];
        S->top--;
        return e;
    }
}
void inQueue(SqQueue *Q,char e){
    if(Q->bottom == 100 - 1){
        printf("队满!\n");
    }else{
        Q->data[Q->bottom] = e;
        Q->bottom++;
    }
}

char outQueue(SqQueue *Q){
    char r = '1';
    if(Q->top == Q->bottom){
        printf("队空!\n");
    }else{
        r = Q->data[Q->top];
        Q->top++;
    }
    return r;
}

void Init_queue(SqQueue *Q){
    if(!Q){
        printf("初始化失败!\n");
    }else{
        Q->top = Q->bottom = 0;
    }
}
void Init_Stack(SqStack  *S)
{
    if(!S){
            printf("初始化失败!\n");
        }else{
            S->bottom  =  S->top = 0 ;
        }
}

void printS(SqStack *S){
    int lon = S->top - S->bottom;
    if(lon == 0){
        printf("栈空!\n");
    }else{
        for(int i = 1 ; i <= lon;i++){
            printf("%c ",S->data[i]);
        }
        printf("\n");
    }
}


int main(){
    SqStack S;
    SqQueue Q;
    Init_queue(&Q);
    Init_Stack(&S);
    char bb[9] = "tsaedsae";
    char aa[4] = "sae";
    scanf("%s",say);getchar();
    int lon = strlen(say);
    printf("%d\n",lon);
    for(int i = lon -1;i >=0;i--){
        printf("逆向入栈:%c\n",say[i]);
        ruZhan(&S,say[i]);
        if(S.data[S.top - 1] == ')'){
            char x = chuZhan(&S);
            if(x == '('){
                printf("栈顶出栈元素是'('时出栈:')' \n");
                chuZhan(&S);
                int lon2 = Q.bottom - Q.top;
                char pp = Q.data[Q.bottom-1];
                lon2--;
                while(lon2--){
                    ruZhan(&S,pp);
                    ruZhan(&S,outQueue(&Q));
                }
                ruZhan(&S,pp);
            }else{
               inQueue(&Q,x);
               printf("栈顶第2个元素是')'时出栈:%c 并入队:%c\n",x,x);
            }
        }
    }
    printS(&S);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/expedition/p/12207167.html