Cover image for LeetCode 150 Interview Questions P150 Evaluate Reverse Polish Notation

LeetCode 150 Interview Questions P150 Evaluate Reverse Polish Notation


Timeline

timeline

2025-11-19

init

stack

Problem:

Classic problem. Here, since the problem guarantees the reverse Polish expression is valid, no validation is performed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <string>
#include <vector>
#include <stack>

using std::vector;
using std::string;
using std::stack;

class Solution {
public:
int evalRPN(vector<string> &tokens)
{
stack<int> st;
int val1, val2, res = 0;
for (string &token : tokens) {
if (!token.compare("+") || !token.compare("-") || !token.compare("*") || !token.compare("/")) {
val1 = st.top();
st.pop();
val2 = st.top();
st.pop();
if (!token.compare("+"))
st.push(val2 + val1);
else if (!token.compare("-"))
st.push(val2 - val1);
else if (!token.compare("*"))
st.push(val2 * val1);
else if (!token.compare("/"))
st.push(val2 / val1);
} else {
st.push(std::stoi(token));
}
}
return st.top();
}
};