java逆波兰(后缀表达式)计算器实现

代码:

package course;

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

public class PolandNotation {
	public static void main(String[] args) {
		
		// 完成将一个中缀表达式转换成后缀表达式的功能
		// 说明
		// 1. 1+((2+3)*4)-5 ==> 转成  1 2 3 + 4 * + 5 -
		// 2. 因为直接对字符串进行操作不方便,因此先将"1+((2+3)*4)-5" => 中缀表达式对应的list
		//    即"1+((2+3)*4)-5" => ArrayList[1,+,(,(,2,+,3,),*,4,),-,5]
		// 3. 将得到的中缀表达式对应的list转成后缀表达式对应的list
		//   即ArrayList[1,+,(,(,2,+,3,),*,4,),-,5] ==> ArrayList[1,2,3,+,4,*,+,5,-]
		String expression = "1+((2+3)*4)-5";
		List<String> infix = toInfixExpressionList(expression);
		System.out.println("中缀表达式对应的List=" + infix); // ArrayList[1,+,(,(,2,+,3,),*,4,),-,5]
		List<String> suffix = parseSuffixExpressionList(infix);
		System.out.println("后缀表达式对应的List=" + suffix);
		
		System.out.printf("expresstion=%d", calculate(suffix));
		
		/*
		// 先定义一个逆波兰表达式
		// (3+4)*5-6=> 3 4 + 5 * 6 - => 29
		// 为了方便,逆波兰表达式的数字和符号用空格隔开
		String suffixExpression = "3 4 + 5 * 6 -";
		// 思路
		// 1. 先将" 3 4 + 5 * 6 - "放到ArrayList中
		// 2. 将ArrayList传给一个方法,遍历ArrayList配合栈完成计算
		List<String> rpnList = getListString(suffixExpression);
		System.out.println("rpnList=" + rpnList);
		
		int res = calculate(rpnList);
		System.out.println("计算的结果为:" + res);
		*/
	}
	
	// ArrayList[1,+,(,(,2,+,3,),*,4,),-,5] ==> ArrayList[1,2,3,+,4,*,+,5,-]
	// 方法:将得到的中缀表达式对应的list转成后缀表达式对应的list
	public static List<String> parseSuffixExpressionList(List<String> ls) {
		// 定义两个栈
		Stack<String> s1 = new Stack<>(); // 符号栈
		// 说明:因为s2这个栈在整个转换过程中没有pop操作,而且后面还需要逆序输出
		// 因此比较麻烦,这里就不用Stack,直接使用List
		List<String> s2 = new ArrayList<>(); // 存储中间结果的List
		
		// 遍历ls
		for (String item: ls) {
			// 如果是一个数,加入s2
			if (item.matches("\\d+")) {
				s2.add(item);
			} else if (item.equals("(")) {
				// 如果是左括号直接压入s1
				s1.push(item);
			} else if (item.equals(")")) {
				// 如果是右括号,依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这对括号丢弃
				while (!s1.peek().equals("(")) {
					s2.add(s1.pop());
				}
				s1.pop(); // 将左括号弹出栈
			} else {
				// 当item的优先级小于等于s1栈顶运算符的优先级,将s1栈顶的运算符弹出并加入到
				// s2中,然后再次转到(4-1)与s1新的栈顶运算符相比较
				while (s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item)) {
					s2.add(s1.pop());
				}
				// 如果s1为空,或栈顶运算符为左括号"(",则直接将此运算符入栈
				if (s1.isEmpty() || s1.peek() == "(")
					s1.push(item);
				// 若优先级比栈顶运算符的高,将运算符压入s1
				if (Operation.getValue(item) > Operation.getValue(s1.peek()))
					s1.push(item);
			}
		}
		
		// 将s1中剩余的运算符依次弹出并加入s2中
		while (s1.size() != 0) {
			s2.add(s1.pop());
		}
		
		return s2; // 注意因为是存放到List,因此按顺序输出就是对应的后缀表达式对应的List
	}
	
	// 方法:将中缀表达式转成对应的list
	// s="1+((2+3)*4)-5"
	public static List<String> toInfixExpressionList(String s) {
		// 定义一个List,存放中缀表达式对应的内容
		List<String> ls = new ArrayList<String>();
		int i = 0; // 这是一个指针,用于遍历中缀表达式字符串
		String str; // 对多位数的拼接
		char c; // 每遍历到一个字符就放入到c中
		do {
			// 如果c是一个非数字,就需要加入到ls
			if ((c = s.charAt(i)) < '0' || (c = s.charAt(i)) > '9') {
				ls.add("" + c);
				i++; // i需要后移
			} else { // 如果是一个数,需要考虑多位数的问题
				str = ""; // 先将str置空
				while(i < s.length() && (c=s.charAt(i)) >= '0' && (c=s.charAt(i)) <= '9') {
					str += c; // 拼接
					i++;
				}
				ls.add(str);
			}
		} while (i < s.length());
		return ls;
	}
	
	// 将一个逆波兰表达式依次将数据和运算符放到ArrayList中
	public static List<String> getListString(String suffixExpression) {
		// 将suffixExpression分割
		String[] split = suffixExpression.split(" ");
		List<String> list = new ArrayList<String>();
		for (String ele: split) {
			list.add(ele);
		}
		return list;
	}
	
	// 完成对逆波兰表达式的运算
	// 1. 从左至右扫描,将3和4压入堆栈
	// 2. 遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈
	// 3. 将5入栈
	// 4. 接下来是*运算符,因此弹出5和7,计算出7*5=35,将35入栈
	// 5. 将6入栈
	// 6. 最后是-运算符,计算出35-6的值,即29,由此得出最终结果
	public static int calculate(List<String> ls) {
		// 创建一个栈,只需要一个栈即可
		Stack<String> stack = new Stack<String>();
		// 遍历ls
		for (String item: ls) {
			// 这里使用正则表达式来取出数
			if (item.matches("\\d+")) { // 匹配多位数
				// 入栈
				stack.push(item);
			} else {
				// pop出两个数,并运算,再入栈
				int num2 = Integer.parseInt(stack.pop());
				int num1 = Integer.parseInt(stack.pop());
				int res = 0;
				if (item.equals("+")) {
					res = num1 + num2;
				} else if (item.equals("-")) {
					res = num1 - num2;
				} else if (item.equals("*")) {
					res = num1 * num2;
				} else if (item.equals("/")) {
					res = num1 / num2;
				} else {
					throw new RuntimeException("运算符有误");
				}
				// 把res入栈
				stack.push(res + "");
			}
		}
		// 最后留在stack中得数据是运算结果
		return Integer.parseInt(stack.pop());
	}
}

// 编写一个类Operation,可以返回一个运算符对应的优先级
class Operation {
	private static final int ADD = 1;
	private static final int SUB = 1;
	private static final int MUL = 2;
	private static final int DIV = 2;
	
	// 写一个方法返回对应的优先级数字
	public static int getValue(String operation) {
		int result = 0;
		switch (operation) {
		case "+":
			result = ADD;
			break;
		case "-":
			result = SUB;
			break;
		case "*":
			result = MUL;
			break;
		case "/":
			result = DIV;
			break;
		default:
			System.out.println("不存在该运算符");
			break;
		}
		return result;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值