码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode - Evaluate Reverse Polish Notation

时间:2017-06-21 18:26:02      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:article   push   ==   data   cpp   pre   atoi   ++   include   

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


#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();
	}
};


Leetcode - Evaluate Reverse Polish Notation

标签:article   push   ==   data   cpp   pre   atoi   ++   include   

原文地址:http://www.cnblogs.com/lytwajue/p/7060909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!