算法-第四版-练习1.3.11解答

来源:互联网 发布:打扮家 知乎 编辑:程序博客网 时间:2024/05/01 09:36

问题

编写一段程序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 - * *31 2 3 4 5 * + 6 * * +277

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

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


0 0
原创粉丝点击