1、题目给出一个后缀表达式,要求用队列的形式来操作依旧可以正确运算,求用队列形式操作的表达式。刚开始我没读懂题意,后来明白题目要求两种方式要“用同样的法则”,什么意思呢?法则就是:遇到数字push,遇到运算符pop两个。但是两种方式的push和pop的定义是不同的,所以表达式是不同的。
2、看了别人的思路,说是后缀表达式建树+二叉树的层次遍历。仔细想想确实有道理,但我不知道最初的那个人是如何想到这种思路的。罢了,权当练习二叉树吧。
3、本题虽属于“Lists”分类,但主要考察的是树。二叉树的代码看似复杂,其实熟悉后还是很好用的。以后这个可以当模板。一次AC。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
using namespace std;
typedef struct Tnode
{
bool have_value;
char v;
struct Tnode *left,*right;
}Node;
Node* root;
Node* stack[10010],*q[10010];
char ans[10010],s[10010];
int num;
Node* newnode(void)
{
Node*u=(Node*)malloc(sizeof(Node));
if(u!=NULL)
{
u->have_value=false;
u->left=u->right=NULL;
}
return u;
}
void addnode(Node*x,Node*y,Node*opt)
{
opt->left=x;
opt->right=y;
return;
}
int bfs(void)
{
int front=0,rear=1;
root=stack[0];
q[0]=root;
while(front<rear)
{
Node*u=q[front++];
if(!u->have_value)return 0;
ans[num++]=u->v;
if(u->left!=NULL) q[rear++]=u->left;
if(u->right!=NULL)q[rear++]=u->right;
}
return 1;
}
void remove_tree(Node*u)
{
if(u==NULL) return;
remove_tree(u->left);
remove_tree(u->right);
free(u);
}
int main(void)
{
int test,i,n,top;
Node*opnode;
scanf("%d",&test);
while(test--)
{
memset(s,'\0',sizeof(s));
memset(ans,'\0',sizeof(ans));
scanf("%s",s);
n=strlen(s);top=-1;
for(i=0;i<n;i++)
{
if(islower(s[i]))
{
top++;
stack[top]=newnode();
stack[top]->have_value=true;
stack[top]->v=s[i];
}
if(isupper(s[i]))
{
opnode=newnode();
opnode->have_value=true;
opnode->v=s[i];
addnode(stack[top-1],stack[top],opnode);
stack[top-1]=opnode;
top--;
}
}
bfs();
num=strlen(ans);
while(num>0)
{
printf("%c",ans[num-1]);
num--;
}
printf("\n");
remove_tree(root);
}
return 0;
}