




Sponsored
Sponsored
The stack-based approach is ideal for evaluating Reverse Polish Notation (RPN) expressions because it naturally follows the Last-In-First-Out (LIFO) principle, which aligns with the evaluation order of RPN expressions. The key idea is to iterate through the tokens, pushing operands onto the stack, and handling operators by popping the required number of operands from the stack, performing the operation, and pushing the result back onto the stack.
Time Complexity: O(n), where n is the number of tokens.
Space Complexity: O(n) due to stack usage.
1#include <vector>
2#include <string>
3
4int evalRPN(std::vector<std::string>& tokens) {
5    std::vector<int> stack;
6    for (const std::string& token : tokens) {
7        if (token == "+" || token == "-" || token == "*" || token == "/") {
8            int b = stack.back(); stack.pop_back();
9            int a = stack.back(); stack.pop_back();
10            if (token == "+") stack.push_back(a + b);
11            else if (token == "-") stack.push_back(a - b);
12            else if (token == "*") stack.push_back(a * b);
13            else stack.push_back(a / b);
14        } else {
15            stack.push_back(std::stoi(token));
16        }
17    }
18    return stack.back();
19}
20This solution maintains a vector used as a stack. Iterating through tokens:
The evaluation result is retrieved from the top of the stack at completion.