UVA 11234-Expressions

来源:互联网 发布:h3c 端口带宽利用率 编辑:程序博客网 时间:2024/05/16 12:38

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;}
0 0
原创粉丝点击