这道题是要将一个用栈储存的逆波兰表达式,转化为用队列表示。逆波兰的栈表示就是一个二叉树的后序遍历,我把逆波兰的二叉树画出来后,跟示例一比发现要输出的就是这个树的层次遍历的逆序。照这么写果然过了,但是不明白为什么,上网也没搜到好的结果。
#include <iostream>
#include<cstdio>
using namespace std;
#define max 10010
struct node{
node *l,*r;
char c;
node(char cc){l=r=NULL; c=cc;}
};
int main()
{
node *sta[max],*que[max]; char s[max];
int t; cin>>t; getchar();
while(t--){
gets(s);
int top=0,i=-1;
while(s[++i]!=0){
char c=s[i];
node *p=new node(c);
if(c>='a'&&c<='z') sta[++top]=p;
else{
p->l=sta[top-1]; p->r=sta[top]; sta[--top]=p;
}
}
int front=0,tail=1; que[0]=sta[top];
while(front<tail){
node *p=que[front];
if(p->l!=NULL) que[tail++]=p->l;
if(p->r!=NULL) que[tail++]=p->r;
front++;
}
for(int i=tail-1;i>=0;i--) cout<<que[i]->c;
cout<<endl;
}
return 0;
}