求源代码!!想回家好好过年

解决方案 »

  1.   

    List<Object> toSuffix(String s) {
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("+", 0);
    map.put("-", 0);
    map.put("*", 1);
    map.put("/", 1);
    map.put("(", -1);
    s = s.trim();
    List<Object> list = new ArrayList<Object>();
    String numberRegex = "\\d+";
    String operatorRegex = "\\+|\\-|\\*|/|(|)";
    String regex = numberRegex + "|[" + operatorRegex + "]";
    Matcher matcher = Pattern.compile(regex).matcher(s);
    Stack<String> stack = new Stack<String>();
    while (matcher.find()) {
    String t = matcher.group();
    if (t.equals("(")) {
    stack.push(t);
    } else if (t.equals(")")) {
    while (!stack.peek().equals("(")) {
    list.add(stack.pop());
    }
    stack.pop();
    } else if (map.containsKey(t)) {
    while (!stack.isEmpty() && map.get(t) <= map.get(stack.peek())) {
    list.add(stack.pop());
    }
    stack.push(t);
    } else {
    list.add(Double.parseDouble(t));
    }
    }
    while (!stack.isEmpty()) {
    list.add(stack.pop());
    }
    return list;
    }
    double calculate(List<Object> list) {
    Stack<Double> stack = new Stack<Double>();
    for (Object obj : list) {
    if (obj instanceof Double) {
    stack.push((Double) obj);
    } else {
    double b = stack.pop();
    double a = stack.pop();
    if (obj.equals("+"))
    stack.push(a + b);
    if (obj.equals("-"))
    stack.push(a - b);
    if (obj.equals("*"))
    stack.push(a * b);
    if (obj.equals("/"))
    stack.push(a / b);
    }
    }
    return stack.pop();
    }