leetcode 150 逆波兰表达式

用栈的结构就能很好的实现,贴代码

 1 class Solution {
 2 public:
 3     int evalRPN(vector<string>& tokens) 
 4     {
 5         stack<int> st;
 6         int n = tokens.size();
 7         for(int i = 0 ; i < n ; i++)
 8         {
 9             if(isNumber(tokens[i]))
10             st.push(toint(tokens[i]));
11             else
12             {
13                 int b = st.top();
14                 st.pop();
15                 int a = st.top();
16                 st.pop();
17                 st.push(calculate(a,b,tokens[i]));
18             }
19             cout<<st.top()<<endl;          
20         }
21         return st.top();        
22     }
23     bool isNumber(string s)
24     {
25         if(isdigit(s[0]) || (s[0] == '-' && s.length()>1))
26         return true;
27         else
28         return false;
29     }
30     int calculate(int a,int b,string s)
31     {
32         if(s == "+")
33         return a+b;
34         else if(s == "-")
35         return a-b;
36         else if(s == "*")
37         return a*b;
38         else
39         return a/b;        
40     }
41     int toint(string s)
42     {
43         if(s[0] == '-')
44         return -1*atoi(s.substr(1).c_str());
45         else
46         return atoi(s.c_str());
47     }
48 };

 

posted @ 2021-09-14 15:32  zhaohhhh  阅读(34)  评论(0)    收藏  举报