栈的应用   逆波兰式

来源:互联网 发布:乐宝是什么软件 编辑:程序博客网 时间:2024/05/01 19:37
#define _CRT_SECURE_NO_WARNINGS 1#pragma once#include<iostream>#include<assert.h>#include<stack>using namespace std;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(){//vector<Cell>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

0 0