中缀表达式、后缀表达式

中缀表达式和后缀表达式的转换

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Test1 {
	public static void main(String[] args) {
		String ss = "1+((2+3)*4)-5";
		List<String> ls =  infixExp(ss);
		System.out.println(ls);
		List<String> sufL = sufList(ls);
		System.out.println(sufL);
		System.out.print(cal(sufL));
		
	}
	
	public static List<String> sufList(List<String> lls){
		Stack<String> stack = new Stack<String>();
		List<String> suf = new ArrayList<String>();
		for(String s:lls) {
			if(s.matches("\\d+")) {
				suf.add(s);
			}else if(s.equals("(")) {
				stack.add(s);
			}else if(s.equals(")")) {
				while(true) {
					if(!stack.peek().equals("(")) {
						suf.add(stack.pop());
					}else {
						break;
					}
				}
				stack.pop();
			}else {
				while(stack.size() != 0 && Operation.getValue(stack.peek()) >= Operation.getValue(s)) {
					suf.add(stack.pop());
				}
				stack.push(s);
			}
		}
		
		while(true) {
			if(stack.size() == 0) {
				break;
			}
			suf.add(stack.pop());
		}
		return suf;
	}
	public static List<String> infixExp(String s){
		List<String> ls = new ArrayList<String>();
		String str = "";
		char c = ' ';
		int index = 0;
		while(true) {
			if(index >= s.length()) {
				break;
			}
			c = s.charAt(index);
			if(c < 48 || c > 57) {
				ls.add(""+c);
			}else {
				if(index == s.length()-1) {
					str+=c;
					ls.add(str);
				}else {
					if(s.charAt(index+1) >= 48 && s.charAt(index+1) <= 57) {
						str+=c;
					}else{
						str+=c;
						ls.add(str);
						str="";
					}	
				}
			}
			index++;
		}
		return ls;
	}
	
	public static int cal(List<String> ls) {
		Stack<String> stack = new Stack<String>();
		int index = 0;
		while(true) {
			if(index >= ls.size()) {
				break;
			}
			String s = ls.get(index);
			if(s.matches("\\d+")) {
				stack.push(s);
			}else {
				int num2 = Integer.parseInt(stack.pop());
				int num1 = Integer.parseInt(stack.pop());
				int res = 0;
				if(s.equals("+")) {
					res = num1 + num2;
				}
				else if(s.equals("-")) {
					res = num1 - num2;
				}
				else if(s.equals("*")) {
					res = num1 * num2;
				}
				else if(s.equals("/")) {
					res = num1 / num2;
				}else {
					System.out.println("符号有问题!");
				}
				stack.push(res+"");
			}
			index++;
		}
	return 	Integer.parseInt(stack.pop());
	}
}
class Operation {
	private static int ADD = 1;
	private static int SUB = 1;
	private static int MUL = 2;
	private static int DIV = 2;
	public static int getValue(String string) {
		int result = 0;
		switch(string) {
			case "+":
				result = ADD;
				return result;
			case "-":
				result = SUB;
				return result;
			case "*":
				result = MUL;
				return result;
			case "/":
				result = DIV;
				return result;
			default:
				break;
		}
		return result;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_56127002/article/details/131579740