zoukankan      html  css  js  c++  java
  • 算法-第四版-练习1.3.11解答

    问题

    编写一段程序EvaluatePostfix,从标准输入中得到一个后序表达式,求值并打印结果。

    解决思路

    后序表达式求解起来比较简单,读到数放入堆栈中,读到运算符,从堆栈中取数字进行运算,然后将结果放回堆栈。最后堆栈中只有一个元素,就是表达式的值。


    代码

    /**
     * Description : 
     * Author      : mn@furzoom.com
     * Date        : Oct 20, 2016 1:36:55 PM
     * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved.
     */
    package com.furzoom.lab.algs.ch103;
    
    import java.util.Scanner;
    
    /**
     * ClassName    : E10311 <br>
     * Function     : TODO ADD FUNCTION. <br>
     * date         : Oct 20, 2016 1:36:55 PM <br>
     * 
     * @version 
     */
    public class E10311
    {
        private static int evaluatePostfix(String s)
        {
            String[] params = s.split(" ");
            Stack<Integer> stack = new Stack<Integer>();
            for (String param : params) {
                if (param.equals("+")) {
                    int d2 = stack.pop();
                    int d1 = stack.pop();
                    stack.push(d1 + d2);
                } else if (param.equals("-")) {
                    int d2 = stack.pop();
                    int d1 = stack.pop();
                    stack.push(d1 - d2);
                } else if (param.equals("*")) {
                    int d2 = stack.pop();
                    int d1 = stack.pop();
                    stack.push(d1 * d2);
                } else if (param.equals("/")) {
                    int d2 = stack.pop();
                    int d1 = stack.pop();
                    stack.push(d1 / d2);
                } else { // number
                    stack.push(Integer.parseInt(param));
                }
            }
            return stack.pop();
        }
        
        public static void main(String[] args)
        {
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                System.out.println(evaluatePostfix(scanner.nextLine()));
            }
            scanner.close();
        }
    }
    

    结果:

    1 2 + 3 4 - 5 6 - * *
    3
    1 2 3 4 5 * + 6 * * +
    277

    算法-第四版-1.3 背包、队列和栈-习题索引汇总

    算法-第四版习题索引汇总


  • 相关阅读:
    maquee 无缝轮播
    pascal语言中学版整理
    SPFA
    Bellman—Ford算法思想
    序列化
    random 模块 时间模块(time) sys模块 os模块
    1、正则表达式
    1、__del__ 2、item系列 3、__hash__ 4、__eq__
    小总结 面向对象
    1、面向对象内置函数 2、反射 3、内置方法
  • 原文地址:https://www.cnblogs.com/furzoom/p/7710192.html
Copyright © 2011-2022 走看看