• 算法-第四版-练习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 背包、队列和栈-习题索引汇总

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


  • 相关阅读:
    CF1540B Tree Array
    CF1539F Strange Array
    CF526F Pudding Monsters
    怎样用 VS 2017 编译 cpprestsdk 库
    【转】C语言中常见的内存错误与解决方法
    vs2019 windbg方式远程调试应层程序
    关于 类似QQ 长截图的方案
    AIX小型机
    vSphere
    Git的使用
  • 原文地址:https://www.cnblogs.com/furzoom/p/7710192.html
Copyright © 2020-2023  润新知