UVA 11234-Expressions
题目大意:小写字母代表数字,大写字母代表运算,将用栈的方式存储运算式改成用队列存储的运算式
解题思路:用栈建数,用队列层次遍历数
#include <stdio.h>
#include <stack>
#include <queue>
#include <iostream>
using namespace std;
class tree {
public:
tree *l;
tree *r;
char x;
tree(char y) {
l = r = NULL;
x = y;
}
};
int main() {
stack<tree*> sta;
queue<tree*> que;
char re[1000000];
int n;
cin >> n;
getchar();
while(n--) {
char c;
while(scanf("%c", &c) && c != '\n') {
tree *p = new tree(c);
if(c >= 'a' && c <= 'z' )
sta.push(p);
else {
p->l = sta.top();
sta.pop();
p->r = sta.top();
sta.pop();
sta.push(p);
}
}
tree *p = sta.top();
que.push(p);
int m = 0;
while(!que.empty()) {
if(que.front()->r != NULL)
que.push(que.front()->r);
if(que.front()->l != NULL)
que.push(que.front()->l);
re[m] = que.front()->x;
m++;
que.pop();
}
for(int i = m - 1; i >= 0; i--) {
cout << re[i];
}
cout << endl;
}
return 0;
}