11234 - Expressions*****

本文介绍了一种使用队列实现后缀表达式序列化的方法,包括栈、队列、二叉树的应用,并提供了两种实现方式,一种为非指针实现,另一种为指针实现,后者已通过验证。
/* 题意:根据后缀表达式,输出使用队列实现相同效果的序列 需要用到栈、队列、二叉树 */ //无指针,推荐,可是未通过!!! #include <iostream> #include <string> #include <stack> #include <queue> #include <cstring> #include <cstdio> using namespace std; const int kMax=10007; struct Node { int parent,left,right; }tree[kMax]; int ans[kMax]; int main() { /* freopen("data.in","r",stdin); freopen("data.out","w",stdout); //*/ int T; scanf("%d",&T); while(T--) { stack<int> s; memset(tree,-1,sizeof(tree)); string line; cin>>line; for(int i=0;i<line.size();i++) { if(islower(line[i])) s.push(i); else { int x,y; y=s.top(); s.pop(); x=s.top(); s.pop(); tree[i].left=x; tree[i].right=y; tree[x].parent=tree[y].parent=i; s.push(i); } } int root; for(int i=0;i<line.size();i++) { if(tree[i].parent==-1) { root=i; break; } } queue<int> q; q.push(root); int u=0; memset(ans,0,sizeof(ans)); while(!q.empty()) { int x=q.front(); q.pop(); ans[u++]=x; if(tree[x].left!=-1) q.push(tree[x].left); if(tree[x].right!=-1) q.push(tree[x].right); } for(int i=u-1;i>=0;i--) printf("%c",line[ans[i]]); printf("\n"); } return 0; }//指针实现,通过 #include <iostream> #include <string> #include <stack> #include <queue> #include <cstring> #include <cstdio> using namespace std; const int kMax=10007; char ans[kMax]; struct TNode { char op; TNode *left,*right; }; TNode *creatTree(char a=0,TNode *lchild=NULL,TNode *rchild=NULL) { TNode *tree=new TNode; tree->left=lchild; tree->right=rchild; tree->op=a; return tree; } int main() { /* freopen("data.in","r",stdin); freopen("data.out","w",stdout); //*/ int T; scanf("%d",&T); while(T--) { stack<TNode *> s; string line; cin>>line; for(int i=0;i<line.size();i++) { if(islower(line[i])) { TNode *tree=creatTree(line[i]); s.push(tree); } else { TNode *l_child,*r_child; r_child=s.top(); s.pop(); l_child=s.top(); s.pop(); TNode *tree=creatTree(line[i],l_child,r_child); s.push(tree); } } TNode *root=s.top(); queue<TNode *> q; q.push(root); int u=0; memset(ans,0,sizeof(ans)); while(!q.empty()) { TNode *tree=q.front(); q.pop(); ans[u++]=tree->op; if(tree->left!=NULL) q.push(tree->left); if(tree->right!=NULL) q.push(tree->right); } for(int i=u-1;i>=0;i--) printf("%c",ans[i]); printf("\n"); } return 0; }


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值