1: #include <stdio.h>
2: #include <stdlib.h>
3: #define STACK_INIT_SIZE 20
4: #define STACKINCREMENT 10
5:
6: typedef char ElemType; /*将char类型定义为ElemType*/
7: typedef struct { /*定义一个栈类型*/
8: ElemType *base;
9: ElemType *top;
10: int stacksize;
11: } sqStack;
12:
13:
14: void initStack(sqStack *s)
15: {
16: /*内存中开辟一段连续空间作为栈空间,首地址赋值给s->base*/
17: s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
18:
19: if(!s->base) exit(0); /*分配空间失败*/
20:
21: s->top = s->base; /*最开始,栈顶就是栈底*/
22: s->stacksize = STACK_INIT_SIZE; /*最大容量为STACK_INIT_SIZE */
23: }
24:
25: void Push(sqStack *s, ElemType e) { /*入栈操作*/
26: if(s->top - s->base >= s->stacksize) {
27: /*栈满,追加空间*/
28: s->base = (ElemType *)realloc(s->base, (s->stacksize +
29: STACKINCREMENT) * sizeof(ElemType));
30:
31: if(!s->base) exit(0); /*存储分配失败*/
32:
33: s->top = s->base + s->stacksize;
34: s->stacksize = s->stacksize + STACKINCREMENT; /*设置栈的最大容量*/
35: }
36:
37: *(s->top) = e; /*放入数据*/
38: s->top++;
39: }
40:
41: void Pop(sqStack *s , ElemType *e) { /*出栈操作*/
42: if(s->top == s->base) return; /*将栈顶元素弹出*/
43:
44: *e = *--(s->top); /*修改栈顶指针*/
45: }
46:
47: int StackLen(sqStack s) { /*获得栈s的大小*/
48: return (s.top - s.base) ;
49: }
50:
51:
52: void translate(ElemType e, sqStack *s) {
53: ElemType c , a;
54: sqStack ss1;
55:
56: if(e >= 97 && e <= 122 ) printf("%c", e);
57: else if(e == 'A') printf("%s", "sae");
58: else if(e == 'B') printf("%s", "tsaedsae");
59: else if(e == '(')
60: {
61:
62: initStack(&ss1); /*初始化栈ss1,用来将括号里面的内容从栈中取出*/
63: Pop(&(*s), &c); /*注意*s相当于主函数中的s*/
64: a = c; /*保留括号后的第一个元素*/
65: Pop(&(*s), &c);
66:
67: while(c != ')') {
68: Push(&ss1, a);
69: Push(&ss1, c);
70: Pop(&(*s), &c);
71: }
72:
73: Push(&ss1, a); /*并按语法规定排列后从右至左进入一个新栈ss1*/
74:
75: while(StackLen(ss1)) /*翻译括号里的内容*/
76: {
77: Pop(&ss1, &c); /*取出ss1中的元素c*/
78: translate(c, &ss1); /*递归地调用函数 translate对元素c进行翻译*/
79: }
80: }
81: }
82:
83: int main()
84: {
85: ElemType e;
86: sqStack s1, s2;
87: initStack(&s1); /*初始化栈s1*/
88:
89: printf("Please input Devil language:\n");
90: scanf("%c", &e);
91:
92: while(e != '#')
93: {
94: if(e == 'A' || e == 'B' || (e >= 97 && e <= 122) || e == '(' || e == ')')
95: { /*输入的魔王语言合法*/
96: Push(&s1, e); /*入栈*/
97:
98: }
99:
100: scanf("%c", &e);
101: }
102:
103:
104: initStack(&s2); /*初始化栈s2*/
105:
106: while(StackLen(s1))
107: {
108: Pop(&s1, &e);
109: //printf("%c\n",e);
110: Push(&s2, e); /*将魔王语言从右至左入栈s2*/
111: }
112:
113: printf("The mankind language is:\n");
114:
115: while(StackLen(s2))
116: {
117: Pop(&s2, &e);
118: translate(e, &s2) ;
119: }
120:
121: return 0;
122:
123: }