leetcode_Evaluate Reverse Polish Notation

此题是栈的题目,最经典的,也就是后缀表达式求值,遇到整数就压栈,遇到操作符就弹两次栈,并把运算结果压到栈里,最后把栈里的结果弹出来就可以了。

这个题会有很多变种,其实后缀表达式就是运算树的后序遍历,我们平时看到的运算是中序遍历的结果。还可以转换成先序遍历。互相转换。

还有就是注意下迭代器的使用。

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        vector<string>::iterator iter;
        vector<int> temp;
        int number;
        int a,b;
        vector<int>::reverse_iterator riter;
        for (iter = tokens.begin(); iter != tokens.end(); iter++) {
            if (*iter == "+") {
                riter = temp.rbegin();
                a = *riter;
                temp.pop_back();
                riter = temp.rbegin();
                b = *riter;
                temp.pop_back();
                temp.push_back(a+b);
            }else if (*iter == "-"){
                riter = temp.rbegin();
                a = *riter;
                temp.pop_back();
                riter = temp.rbegin();
                b = *riter;
                temp.pop_back();
                temp.push_back(b-a);
            }else if (*iter == "*"){
                riter = temp.rbegin();
                a = *riter;
                temp.pop_back();
                riter = temp.rbegin();
                b = *riter;
                temp.pop_back();
                temp.push_back(a*b);
            }else if (*iter == "/"){
                riter = temp.rbegin();
                a = *riter;
                temp.pop_back();
                riter = temp.rbegin();
                b = *riter;
                temp.pop_back();
                temp.push_back(b/a);
            }else{
                number = atoi(iter->c_str());
                temp.push_back(number);
            }
        }
        riter = temp.rbegin();
        return *riter;
    }
};


你可能感兴趣的:(栈,后序遍历)