后缀表达式的计算

#include"seqlist.h"

template<class T, class Container> //适配器模式
class Stack
{
public:
    Stack()
        :_size(0)
    {}
    void Push(const T& x)
    {
        _con.PushBack(x);
        _size++;

    }
    void Pop()
    {
        _con.PopBack();
        _size--;

    }
    bool Empty() //判空
    {
        return _size == 0;
    }
    int size() //计算栈的长度
    {
        return _size;
    }
    T& top() //返回栈顶元素
    {
        return _con.top();
    }

private:
    Container _con;
    size_t _size;
};

enum TYPE
{
    OP_NUM,
    ADD,
    SUB,
    MUL,
    DIV,
};

struct Exp
{
    TYPE _type;
    int _data;
};

//中缀表达式 12 *(3 + 4)- 6 + 8 / 2
//后缀表达式 12 3 4 + * 6 - 8 2 / +
Exp RPN_Exp[] = {
    OP_NUM, 12,
    OP_NUM, 3,
    OP_NUM, 4,
    ADD ,0,
    MUL, 0,
    OP_NUM, 6,
    SUB, 0,
    OP_NUM, 8,
    OP_NUM, 2,
    DIV, 0,
    ADD, 0,
};
Stack<int, SeqList<int>> s1;

int CountRPN_Exp(Exp* RPN_Exp,int size)
{
    int left = 0, right = 0;
    int res = 0;
    for (int i = 0; i < size; i++)
    {
        switch((RPN_Exp + i)->_type) { case ADD: right = s1.top(); s1.Pop(); left = s1.top(); s1.Pop(); res = left + right; s1.Push(res); break; case SUB: right = s1.top(); s1.Pop(); left = s1.top(); s1.Pop(); res = left - right; s1.Push(res); break; case MUL: right = s1.top(); s1.Pop(); left = s1.top(); s1.Pop(); res = left * right; s1.Push(res); break; case DIV: right = s1.top(); s1.Pop(); left = s1.top(); s1.Pop(); res = left / right; s1.Push(res); break; case OP_NUM: s1.Push((RPN_Exp + i)->_data); break; default: cout << "无法计算" << endl; } } return s1.top(); } void test() { int ret = CountRPN_Exp(RPN_Exp, sizeof(RPN_Exp) / sizeof(RPN_Exp[0])); cout <<ret; } int main() { test(); getchar(); return 0; } /*后缀表达式的计算过程:如果遇到操作数,则入栈。如果该项是操作符,则连续从栈中退出两个操作数 XY,形成运算指令X<op>Y,并将计算结果重新压入栈中,当表达式的所有想都扫描并处理之后,栈顶 存放的就是最后计算结果。*/

你可能感兴趣的:(后缀表达式,逆波兰表达式)