您的位置:首页 > 编程语言 > Lua

[LeetCode]Evaluate Reverse Polish Notation

2014-04-06 10:26 309 查看

这道题主要难点是栈(stack)的使用。

#include <iostream>
#include <string.h>
#include <vector>
#include <stack>
using namespace std;

class Solution {

public:
bool IsOp(string s)
{
if (s == "+" || s == "-" || s == "*" || s == "/")
return true;
else return false;
}

int evalRPN(vector<string> &tokens) {
vector<string>::iterator it;
stack<int> s;
int result = 0;
for (it = tokens.begin(); it != tokens.end(); it++)
{
int a;
if (!IsOp(*it))
{
a = atoi((*it).data());
s.push(a);
}
else
{
char op = (*it).data()[0];
int a = s.top(); s.pop();
int b = s.top(); s.pop();
switch (op)
{
case '+':result = b + a; break;
case '-':result = b - a; break;
case '*':result = b * a; break;
case '/':result = b / a; break;
default:
break;
}
s.push(result);
}
}
return s.top();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: