您的位置:首页 > 其它

Expressions

2015-08-17 20:06 253 查看
Expressions

大意:

貌似是栈可以用来模拟后缀运算符的运算方式,而队列可以用来模拟中缀运算符的运算方式,小写字母代表数字,大写字母代表运算符;

如例1 

xyPzwIM 栈下模拟运算为 (wIz)M(yPx)

wzyxIPM 队列模拟运算为 (wIz)M(yPx)

给出栈下的字符串,求出和栈下运算结果相同的队列字符串;

要点:

可以建立二叉树,遇到小写字母则压入。遇到大写字母,者弹出栈两次,分别作为该字母的右,左节点,将该子树压入栈;

遍历整个栈,逆序输出;

代码:

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stack>
#include <queue>
using namespace std;

#define MAX 10005

struct node{
char data;
node *left;
node *right;
node(char x = 0, node *l = 0, node *r = 0):data(x), left(l), right(r){}
};

node *build(char x, node *l, node *r){
node *root = new node(x, l, r);
return root;
}

int main(){
int num;
scanf ("%d", &num);
getchar();
while (num--){
char str[MAX];
char ans[MAX];
scanf ("%s", str);
stack<node*> stc;
queue<node*> que;
for (int i = 0; i < strlen(str); i++){
if (islower(str[i])){
node *tree = new node(str[i], 0, 0);
stc.push(tree);
}
else {
node *r = stc.top();
stc.pop();
node *l = stc.top();
stc.pop();
stc.push(build(str[i], l, r));
}
}
que.push(stc.top());
int count;
for (count = 0; !que.empty(); count++){
node *cur = que.front();
que.pop();
ans[count] = cur->data;
if (cur->left)
que.push(cur->left);
if (cur->right)
que.push(cur->right);
}
for (int i = count - 1; i >= 0; i--)
printf("%c", ans[i]);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: