#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; #include<assert.h> #pragma once template<class T> class Stack { public: Stack() :_a(0) , _capacity(0) , _top(0) {} Stack(const Stack<T>& s) :_a(new T[s._top]) , _top(s._top) , _capacity(s._top) { for (size_t i = 0; i < _top; ++i) { _a[i] = s._a[i]; } } Stack<T>& operator=(Stack<T> s) { swap(_a, s._a); _top = s._top; _capacity = s._capacity; } ~Stack() { if (_a) { delete[] _a; } } void Push(const T& x) { _CheckCapacity(); _a[_top++] = x; } void Pop() { assert(_top > 0); --_top; } T& Top() { assert(_top > 0); return _a[_top - 1]; } bool Empty() { return _top == 0; } size_t Size() { return _top; } protected: void _CheckCapacity() { if (_top == _capacity) { _capacity = 2 * _capacity + 3; T* tmp = new T[_capacity]; for (size_t i = 0; i < _top; ++i) { tmp[i] = _a[i]; } delete[] _a; _a = tmp; } } protected: T* _a; size_t _top; size_t _capacity; }; template<class T> struct Node { T _data; Node<T>* _next; Node(const T& x) :_data(x) , _next(NULL) {} }; template<class T> class Queue { public: Queue() :_head(NULL) , _tail(NULL) , _size(0) {} Queue(const Queue<T>& q); Queue<T>& operator=(Queue<T> q); ~Queue() { // } public: void Push(const T& x) { if (_head == NULL) { _head = _tail = new Node<T>(x); } else { _tail->_next = new Node<T>(x); _tail = _tail->_next; } ++_size; } void Pop() { assert(_head); if (_head->_next == NULL) { delete _head; _head = _tail = NULL; } else { Node<T>* del = _head; _head = _head->_next; delete del; } --_size; } T& Front() { assert(_head); return _head->_data; } T& Back() { assert(_tail); return _tail->_data; } bool Empty() { return _head == NULL; } size_t Size() { return _size; } protected: Node<T>* _head; Node<T>* _tail; size_t _size; }; enum Type { OP_NUM, OP_SYMBOL, }; enum SYMBOL { ADD, SUB, MUL, DIV, }; struct Cell { Type _type; int _value; }; #include <stack> int CountRNP(Cell a[], size_t size) { assert(a); stack<int> s; for (size_t i = 0; i < size; ++i) { if (a[i]._type == OP_NUM) { s.push(a[i]._value); } else { int right = s.top(); s.pop(); int left = s.top(); s.pop(); switch (a[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; } } } return s.top(); } void TestRNP() { Cell a[] = { { 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 << "运算结果:" << CountRNP(a, sizeof(a) / sizeof(Cell)) << endl; } int main() { TestRNP(); getchar(); return 0; }
本文出自 “顺势而为” 博客,请务必保留此出处http://lk123456.blog.51cto.com/10831443/1763556
原文地址:http://lk123456.blog.51cto.com/10831443/1763556