写一个魔王解释程序,将魔王的话解释成人能听懂的话。
基本要求:设大写字母表示魔王语言的词汇,小写字母表示人的词汇,希腊字母表示可以用大写字母或小写字母代换的变量。用下述两种规则和下述规则(2)实现。
(1) B→tAdA
(2) A→sae
测试数据:B(einxgz)B
B(einxgz)B=>tAdA(einxgz)tAdA=>tsaedsae(einxgz)tsaedsae
=> tsaedsaeezegexeneietsaedsae
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100
//栈结构
typedef struct
{
char list[MAXSIZE];
int top;
}SeqStack;
//队列结构
typedef struct
{
char data[MAXSIZE];
int front, rear;
}SeQueue;
//初始化栈
void InitStack(SeqStack *s)
{
s->top = -1;
}
//判栈空
int IsEmpty(SeqStack *s)
{
if (s->top == -1)
return 1;
return 0;
}
int Push(SeqStack *s, char x)
{
if(s->top == MAXSIZE-1)
{
return 0;
}
else
{
s->top++;
s->list[s->top] = x;
return 1;
}
}
int Pop(SeqStack *s, char *x)
{
if (s->top == -1)
{
return 0;
}
else
{
*x = s->list[s->top];
s->top--;
return 1;
}
}
void InitQueue(SeQueue *q)
{
q->front = q->rear = -1;
}
int EmptyQueue(SeQueue *q)
{
if (q->front == q->rear)
return 1;
return 0;
}
//入队
int InQueue(SeQueue *q, char x)
{
if (q->rear == MAXSIZE-1)
return 0;
else
{
q->rear++;
q->data[q->rear] = x;
return 1;
}
}
//出队
char OutQueue(SeQueue *q)
{
if (q->front == q->rear)
return 0;
else
{
char x;
// x = q->data[q->front];
q->front++;
x = q->data[q->front];
return x;
}
}
int main()
{
char letter[MAXSIZE] = "B(einxgz)B";//输入
int len = strlen(letter);
SeqStack s;
SeQueue q;
InitStack(&s);
InitQueue(&q);
//将()中的字母入栈
for (int i = 0; i < len; i++)
{
if (letter[i] == '(')
{
int flag = i+1;
int x = i+2;
Push(&s, letter[flag]);
while(letter[x] != ')')
{
Push(&s, letter[x]);
Push(&s, letter[flag]);
x++;
}
}
}
//将所有字母入队
for (int i = 0; i < len; i++)
{
//括号中字母出栈入队,实现倒序
if (letter[i] == '(')
{
while(s.top != -1)
{
char ch;
Pop(&s, &ch);
InQueue(&q, ch);
}
//括号后
while(letter[i] != ')')
{
i++;
continue;
}
continue;
}
InQueue(&q, letter[i]);
}
//出队输出
while (q.front != q.rear)
{
char ch = OutQueue(&q);
if (ch >= 'a' && ch <= 'z')
{
printf("%c", ch);
}
else if (ch == 'A')
{
printf("%s", "sae");
}
else if (ch == 'B')
{
printf("%s", "tsaedsae");
}
}
return 0;
}
程序输出如下
tsaedsaeezegexeneietsaedsae