题目大意:一个表达式,可以用栈来处理,同时可以用队列来处理。现在告诉你用栈处理的表达式顺序,求其用队列表示的顺序。几种操作数为小写字母,操作符为大写字母。
解题思路:采用栈来模拟,则为树的后序遍历,而用队列表示的是其层次遍历的逆序输出。所以根据后序遍历建树,再层次遍历该树,逆序输出。即遇到小写字母就建立一个只有根节点的树,并将该地址入栈。遇到大写字母,就建立一个根节点为该大写字母,然后从栈中取出两个地址,分别作为该节点的左右孩子,然后再将该根节点地址入栈。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<ctype.h>
using namespace std;
struct node {
int l;
int r;
} node[10010];
int stack[10010];
char str[10010];
int main() {
int T;
scanf("%d", &T);
while (T--) {
scanf("%s", str);
int tag = 0;
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
stack[tag++] = i;
node[i].l = node[i].r = -1;
}
if (str[i] >= 'A' && str[i] <= 'Z') {
node[i].r = stack[--tag];
node[i].l = stack[--tag];
stack[tag++] = i;
}
}
stack[0] = len - 1;
tag = 1;
int t = 0;
while (tag != len) {
if (node[stack[t]].l != -1) stack[tag++] = node[stack[t]].l;
if (node[stack[t]].r != -1) stack[tag++] = node[stack[t]].r;
t++;
}
for (int i = len -1; i >= 0; i--)
printf("%c", str[stack[i]]);
printf("\n");
}
return 0;
}
写的第一棵树,有点感人qwq