/*
题意:根据后缀表达式,输出使用队列实现相同效果的序列
需要用到栈、队列、二叉树
*/
//无指针,推荐,可是未通过!!!
#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;
}
11234 - Expressions*****
最新推荐文章于 2025-11-26 15:16:48 发布
本文介绍了一种使用队列实现后缀表达式序列化的方法,包括栈、队列、二叉树的应用,并提供了两种实现方式,一种为非指针实现,另一种为指针实现,后者已通过验证。
154

被折叠的 条评论
为什么被折叠?



