原题链接:http://oj.leetcode.com/problems/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
题解:
所谓逆波兰式,即操作符位于操作数之后的表示法,我们常见的表示“三加四”都是表示成“3+4”,这是一种中缀表达式,换成逆波兰式,就应该表示成3 4 +,因此逆波兰式也称“后缀表达式”,具体的关于逆波兰式、中缀表达式、波兰式(即前缀表达式),参见维基百科。
很显然,具体操作符最近的两个数便是与这个操作符对应的操作数,用栈来实现是最直观的,这道题一道比较基础的栈的应用题,详情见代码:
1 #include <cstdio> 2 #include <cstdlib> 3 #include <string> 4 #include <vector> 5 #include <iostream> 6 #include <stack> 7 using namespace std; 8 9 int evalRPN(vector<string> &tokens) 10 { 11 vector<string>::iterator iter; 12 stack<int> res; 13 int a,b; 14 for (iter=tokens.begin();iter!=tokens.end();iter++) 15 { 16 if(*iter=="+" || *iter=="-" || *iter=="*" || *iter=="/") 17 { 18 b = res.top(); 19 res.pop(); 20 a = res.top(); 21 res.pop(); 22 if(*iter=="+") 23 { 24 res.push(a+b); 25 }else if(*iter=="-") 26 { 27 res.push(a-b); 28 }else if(*iter=="*") 29 { 30 res.push(a*b); 31 }else if(*iter=="/") 32 { 33 res.push(a/b); 34 } 35 } 36 else 37 { 38 res.push(atoi((*iter).data())); 39 } 40 } 41 return res.top(); 42 } 43 44 int main() 45 { 46 freopen("in.in","r",stdin); 47 freopen("out.out","w",stdout); 48 49 vector<string> tokens; 50 51 string t; 52 while(!cin.eof()) 53 { 54 cin>>t; 55 tokens.push_back(t); 56 } 57 58 printf("%d ",evalRPN(tokens)); 59 return 0; 60 }