[LeetCode OJ] Evaluate Reverse Polish Notation 解题报告

题目地址:https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/

题意:很简单,就是逆波兰式求值,数据结构基础

要点:顺序遍历数组,数字就入栈,符号就将栈顶的两个元素取出计算后再入栈。结果就是最后栈里的唯一一个元素。

总结:复习了STL中STACK的用法。

#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <stdlib.h>
#include <stdio.h>

using namespace std;
class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        stack<int> sta;
        vector<string>::iterator it;
        for(it = tokens.begin(); it != tokens.end(); ++it){
            string &key = (*it);
            //cout<<key<<endl;
            if(key == "*" || key == "/" || key == "+" || key == "-"){
                int a2 = sta.top();
                sta.pop();
                int a1 = sta.top();
                sta.pop();
                //cout<<a1<<a2<<endl;
                int result = 0;
                switch(key[0]){
                    case '*': {
                        result = a1*a2;
                        break;
                    }
                    case '/': {
                        result = a1/a2;
                        break;
                    }
                    case '+': {
                        result = a1+a2;
                        break;
                    }
                    case '-': {
                        result = a1-a2;
                        break;
                    }
                }
                sta.push(result);
            }
            else{
                int a = atoi(key.c_str());
                sta.push(a);
            }
        }
        int res = sta.top();
        sta.pop();
        return res;
    }
};
点赞