读书人

HDU1237(堆栈使用)

发布时间: 2012-08-02 11:35:25 作者: rapoo

HDU1237(堆栈应用)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1237

package D0724;import java.util.*;public class HDU1237 {static Stack<String> stack1 = new Stack<String>();// 存操作符static Stack<Double> stack2 = new Stack<Double>();// 存操作数public static void main(String[] args) {Scanner sc = new Scanner(System.in);String str;// 接收一行输入double result;//保存最后结果while (sc.hasNextLine()) {str = sc.nextLine();if (str.equals("0"))break;// 初始化变量以及堆栈result = 0;String[] charr = str.split(" ");for (int i = charr.length - 1; i >= 0; i--) {String s = charr[i];if (s.equals("+") || s.equals("-") || s.equals("*")|| s.equals("/"))stack1.push(s);elsestack2.push(Double.valueOf(s));}// System.out.println(stack1.size()+" "+stack2.size());while (!stack1.isEmpty()) {String op1 = stack1.pop();double a = stack2.pop();double b = stack2.pop();//判断是否有第三个操作数double c=0;if (!stack2.isEmpty())c = stack2.pop();// 如果只有一个运算符的时候直接计算a和bif (stack1.isEmpty()) {result = calc(result, op1, a, b);System.out.printf("%.2f", result);System.out.println();} else {// 判断操作符op1和op2优先级String op2 = stack1.pop();if (level(op1, op2)) {result = calc(result, op1, a, b);//注意入栈的顺序stack2.push(c);stack2.push(result);stack1.push(op2);} else {result = calc(result, op2, b, c);//注意入栈的顺序stack2.push(result);stack2.push(a);stack1.push(op1);}}}}}// 操作符比较private static boolean level(String op1, String op2) {if ((op2.equals("*") || op2.equals("/"))&& (op1.equals("+") || op1.equals("-")))return false;return true;}private static double calc(double result, String op1, double a, double b) {//System.out.println(a + op1 + b);char op = op1.charAt(0);switch (op) {case '+':result = a + b;break;case '-':result = a - b;break;case '*':result = a * b;break;case '/':result = a / b;break;default:break;}return result;}}


读书人网 >编程

热点推荐