C++逆波兰表达式的求解
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++逆波兰表达式的求解相关的知识,希望对你有一定的参考价值。
#include <iostream> using namespace std; #include <stack> #include <assert.h> enum Type { OP_SYMBOL, OP_NUM, ADD, SUB, MUL, DIV, }; struct Cell { Type _type; int _value; }; int CountRPN(Cell a[], size_t size) { assert(a != NULL); stack<int> s; while (size--) { if (a->_type == OP_NUM) { s.push(a->_value); } if (a->_type == OP_SYMBOL) { int right = s.top(); s.pop(); int left = s.top(); s.pop(); switch (a->_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: break; } } ++a; } return s.top(); } void TestRPN() { Cell RPNArray[] = { {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(RPNArray, sizeof(RPNArray)/sizeof(RPNArray[0])); } int main() { TestRPN(); return 0; }
本文出自 “zgw285763054” 博客,请务必保留此出处http://zgw285763054.blog.51cto.com/11591804/1782433
以上是关于C++逆波兰表达式的求解的主要内容,如果未能解决你的问题,请参考以下文章