150. Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6


逆波兰计算,大话数据结构中讲到过,用一个栈来实现后缀表达式的计算。

思路:从左到右遍历表达式的每个数字和字符,遇到数字就进栈,遇到符号,就将栈顶的两个数字取出(注意第一次取出的是右操作数,第二次取出的栈顶数字是左操作数),进行运算,将运算结果压栈,一直到最终获得计算结果(最终的栈顶数字)
 1 int evalRPN(vector<string>& tokens)
 2 {
 3     stack<int> s; 
 4     int i;
 5     int result = 0;
 6     //遍历表达式的数字和符号
 7     for (i=0;i<tokens.size();i++)
 8     {
 9         if (tokens[i].c_str() == "+")
10         {
11             int rope = s.top();
12             s.pop();
13             int lope = s.top();
14             s.pop();
15             result = rope + lope;
16             s.push(result);
17         }else if (tokens[i].c_str() == "-")
18         {
19             int rope = s.top();
20             s.pop();
21             int lope = s.top();
22             s.pop();
23             result = rope - lope;
24             s.push(result);
25         }else if (tokens[i].c_str() == "*")
26         {
27             int rope = s.top();
28             s.pop();
29             int lope = s.top();
30             s.pop();
31             result = rope * lope;
32             s.push(result);
33         }else if (tokens[i].c_str() == "/")
34         {
35             int rope = s.top();
36             s.pop();
37             int lope = s.top();
38             s.pop();
39             result = rope / lope;
40             s.push(result);
41         }else
42         {
43             //数字直接进栈
44             s.push(atoi(tokens[i].c_str()));
45         }
46         return s.top();
47     }
48 }
原文地址:https://www.cnblogs.com/tracyhan/p/5490194.html