uva 11234

这道题是要将一个用栈储存的逆波兰表达式,转化为用队列表示。逆波兰的栈表示就是一个二叉树的后序遍历,我把逆波兰的二叉树画出来后,跟示例一比发现要输出的就是这个树的层次遍历的逆序。照这么写果然过了,但是不明白为什么,上网也没搜到好的结果。

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值