zoukankan      html  css  js  c++  java
  • Evaluate Reverse Polish Notation

    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

    • 题目大意:给定一个逆波兰表达式,求该表达式的值
    • 思路:由于逆波兰表达式本身不需要括号来限制哪个运算该先进行,因此可以直接利用栈来模拟计算:遇到操作数直接压栈,碰到操作符直接取栈顶的2个操作数进行计算(注意第一次取出来的是右操作数),然后再把计算结果压栈,如此循环下去。最后栈中剩下的唯一一个元素便是整个表达式的值
    • 实现:
    class Solution {
    public:
        int evalRPN(vector<string> &tokens) {
        	
        	int result = 0;
        	int i;
        	stack<int> opd;         //存储操作数
    		int size = tokens.size();
    		for(i=0;i<size;i++)
    		{
    			if(tokens[i]=="*")
    			{
    				int rOpd = opd.top();   //右操作数 
    				opd.pop();
    				int lOpd = opd.top();  //左操作数 
    				opd.pop();
    				result = lOpd*rOpd;
    				opd.push(result);
    			}
    			else if(tokens[i]=="/")
    			{
    				int rOpd = opd.top();
    				opd.pop();
    				int lOpd = opd.top();
    				opd.pop();
    				result = lOpd/rOpd;
    				opd.push(result);
    			}
    			else if(tokens[i]=="+")
    			{
    				int rOpd = opd.top();
    				opd.pop();
    				int lOpd = opd.top();
    				opd.pop();
    				result = lOpd+rOpd;
    				opd.push(result);
    			}
    			else if(tokens[i]=="-")
    			{
    				int rOpd = opd.top();
    				opd.pop();
    				int lOpd = opd.top();
    				opd.pop();
    				result = lOpd-rOpd;
    				opd.push(result);
    			}
    			else
    			{
    				opd.push(atoi(tokens[i].c_str()));
    			}
    		}
    		return opd.top();
        }
    };
    

      

  • 相关阅读:
    magento 去掉index.php
    TCP三次握手与四次挥手
    <Jper和Iperf>的安装及使用
    【Python】安装方法小结
    【ubuntu】日常网络配置信息的查看及修改
    DNS解析
    【Dig工具】
    【ping/tracert】的简单使用
    【VMvare】yum在线源
    配置文件加载
  • 原文地址:https://www.cnblogs.com/dolphin0520/p/3708587.html
Copyright © 2011-2022 走看看