leetcode150_逆波兰表达式
1、题目
2、分析
用栈来解决问题
3、代码
class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> result; int num1; int num2; for(int i=0; i<tokens.size(); i++){ if (tokens[i]!="+" && tokens[i]!="-" && tokens[i]!="*" && tokens[i]!="/"){ result.push(stoi(tokens[i])); } else{ if(tokens.size()>=2 && tokens[i]=="+"){ num1 = result.top(); result.pop(); num2 = result.top(); result.pop(); result.push(num2+num1); } if(result.size()>=2 && tokens[i]=="-"){ num1 = result.top(); result.pop(); num2 = result.top(); result.pop(); result.push(num2-num1); } if(result.size()>=2 && tokens[i]=="*"){ num1 = result.top(); result.pop(); num2 = result.top(); result.pop(); result.push(num2*num1); } if(result.size()>=2 && tokens[i]=="/"){ num1 = result.top(); std::cout<<"num1 "<<num1<<std::endl; result.pop(); num2 = result.top(); std::cout<<"num2 "<<num2<<std::endl; result.pop(); int num = num2/num1; std::cout<<"num "<<num2/num1<<std::endl; result.push(num); } } } return result.top(); } };
纵一苇之所如,临万顷之茫然。