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;
}
大意:
貌似是栈可以用来模拟后缀运算符的运算方式,而队列可以用来模拟中缀运算符的运算方式,小写字母代表数字,大写字母代表运算符;
如例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;
}
相关文章推荐
- UIMenuController 的使用指南
- kafka的安装和配置
- 算法竞赛入门经典:第七章 暴力求解法 7.4双基回文数
- 算法竞赛入门经典:第七章 暴力求解法 7.3分数拆分
- 8 个不得不说的 MySQL 陷阱
- underscore概况
- 关闭iptables和SELINUX
- CMake 学习
- java环境配置
- 如何提醒客户重载父类的指定方法?
- 装饰者模式(decorator pattern)
- 煤炭行业:如何实现自我救赎?
- HDOJ 2066 一个人的旅行(最短路--dijkstra)
- mongdb 复制集+仲裁(带权限认证)
- 算法竞赛入门经典:第七章 暴力求解法 7.2最大乘积
- Strassen矩阵相乘算法
- wpf 绑定ObservableCollection 的Count属性
- eclipse-hadoop插件
- hdu-1874 畅通工程续
- 数据驱动企业二次腾飞