leetcode150_逆波蘭表達式求值_棧

1. 整體思路,定義數據棧存放數據, 只要遇到運算符就出棧兩個數做加減乘除處理.

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> st;
        for(int i=0;i<tokens.size();i++) {
            if(tokens[i]!="+" && tokens[i]!="-" && tokens[i]!="*" && tokens[i]!="/") {
                int num = stoi(tokens[i]);
                st.push(num);
            }
            else {
                int second = st.top(); st.pop();
                int first = st.top(); st.pop();
                int all = 0;
                if(tokens[i]=="+") all = first+second;
                if(tokens[i]=="-") all = first-second;
                if(tokens[i]=="*") all = first*second;
                if(tokens[i]=="/") all = first/second;
                st.push(all);
            }
        }
        return st.top();
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章