现在的位置: 首页 > 综合 > 正文

Leetcode – Evaluate Reverse Polish Notation

2019年04月17日 ⁄ 综合 ⁄ 共 623字 ⁄ 字号 评论关闭

初看貌似有点复杂,但是搞懂了非常简单,就一个简单的栈应用,每次遇到计算符号"+", "-", "*", "/"就将栈顶端两个数字出栈,计算后再将结果压栈即可。。

#include<iostream>
#include<vector>
#include<stack>
using namespace std;

class Solution {
public:
	int evalRPN(vector<string> &tokens) {
		stack<int> stack;

		for (int i = 0; i < tokens.size(); i++)
		{
			if (tokens[i] == "*" || tokens[i] == "-" || tokens[i] == "+" || tokens[i] == "/")
			{
				int val2 = stack.top();
				stack.pop();

				int val1 = stack.top();
				stack.pop();

				int tmpVal;
				if (tokens[i] == "*")
					tmpVal = val1 * val2;

				else if (tokens[i] == "-")
					tmpVal = val1 - val2;

				else if (tokens[i] == "+")
					tmpVal = val1 + val2;

				else
					tmpVal = val1 / val2;

				stack.push(tmpVal);
			}
			else
			{
				int tmpVal = atoi(tokens[i].c_str());

				stack.push(tmpVal);
			}
		}

		return stack.top();
	}
};

抱歉!评论已关闭.