温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++解逆波兰表达式

发布时间:2020-10-12 05:52:10 来源:网络 阅读:1452 作者:zgw285763054 栏目:编程语言

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;
}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI