UVA 11234-Expressions

本文提供了一种使用栈和队列来转换表达式的算法实现方案,针对UVA11234-Expressions问题,通过构建树形结构并采用层次遍历来完成从栈到队列的表达式转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值