注意:结构实现的巧妙性
#include <iostream>
using namespace std;
#include <assert.h>
#include <stack>
enum Type//定义类型,操作数和操作符
{
OP_SYMBOL,
OP_NUM,
ADD,
SUB,
MUL,
DIV,
};
struct Cell//单元
{
Type _type;
int _value;
};
int CountRPN(Cell *rpn,size_t n)//注意传指针,RPN为数组
{
assert(rpn);
stack<int> s;
for (size_t i = 0; i < n;++i)
{
if (rpn[i]._type == OP_SYMBOL)//注意取操作数时,顺序问题,如左右操作数不同可能影响结果,如:除法
{
int right = s.top();
s.pop();
int left = s.top();
s.pop();
switch (rpn[i]._value)
{
case ADD:
s.push(left + right);
break;
case SUB:
s.push(left - right);
break;
case MUL:
s.push(left * right);
break;
case DIV:
s.push(left / right);
break;
default:
assert(false);
}
}
else if (rpn[i]._type == OP_NUM)
s.push(rpn[i]._value);
}
return s.top();
}
//测试函数
void Funtest()
{
Cell RPN[] =
{
{ OP_NUM, 12 },
{ OP_NUM, 3 },
{ OP_NUM, 4},
{OP_SYMBOL,ADD},
{OP_SYMBOL,MUL},
{OP_NUM,6},
{OP_SYMBOL,SUB},
{ OP_NUM, 8 },
{ OP_NUM,2 },
{OP_SYMBOL,DIV},
{OP_SYMBOL,ADD}
};
cout << CountRPN(RPN, sizeof(RPN) / sizeof(RPN[0]));
}
int main()
{
Funtest();
getchar();
return 0;
}