Java 将中缀表达式转化为后缀表达式实现,有问题,请指出!

justphp 发布于 2014/10/12 23:03
阅读 390
收藏 0
//输入中序表达式 获得 后序表达式	
  public static String convert_suffix_expr(String expr) {
		String result = "", top = "";

		ArrayList<String> al = new ArrayList<String>();

		Pattern pattern = Pattern.compile("[0-9].*");

		String[] str = expr.split(" ");
		
		for (String string : str) {

			Matcher matcher = pattern.matcher(string);
			boolean b = matcher.matches();

			if (b) {
				result += string + " ";

			} else {

				if (al.size() > 0) {
					top = al.get(al.size() - 1);
				}

			
				
				if (string.equals(")")) {

					do {
						if (!(al.get(al.size() - 1).equals("("))) {

							result += al.get(al.size() - 1) + " ";
							al.remove(al.size() - 1);
						}
					} while (al.size() > 0
							&& !al.get(al.size() - 1).equals("("));
					al.remove(al.size() - 1);

				} else if (string.equals("(") || string.equals("*")
						|| string.equals("/")) {

					al.add(string);

				} else {

					if (top.equals("*") || top.equals("/")) {

						do {
							result += al.get(al.size() - 1) + " ";
							al.remove(al.size() - 1);
						} while (al.size() > 0);
						al.add(string);
					} else {
						al.add(string);
					}

				}

			}

		}

		while (al.size() > 0) {
			result += al.get(al.size() - 1) + " ";
			al.remove(al.size() - 1);
		}

		return result;
	}



加载中
返回顶部
顶部