[数据结构]逆波兰计算器分析和实现

逆波兰计算器主要用来解决后缀表达式的运算,一般使用栈结构来进行运算。

例:有一个后缀表达式(3+4)*5-6=29  =>"3 4 + 5 * 6 -"

首先需要利用一个list结构将表达式存储起来。这里就需要一个转换方法:

// 将字符串转换成list
	public static List<String> getListString(String suffixExpression) {
		String[] split = suffixExpression.split(" ");
		List<String> list = new ArrayList<String>();
		for (String str : split) {
			list.add(str);
		}
		return list;
	}

接下来就是分析部分:

1.从左至右扫描判断是数字还是运算符号。

1.1数字则入栈

1.2运算符 则弹出两个数进行运算。-   /   运算注意是后出栈数运算前出栈数 

2.将运算结果入栈

3.数栈中留下的则是运算结果

接下来上代码:

public static int calculate(List<String> list) {
		Stack<String> stack = new Stack<String>();

		for (String item : list) {
			// 正则匹配
			if (item.matches("\\d+")) {
				stack.push(item);
			} else {
				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("符号有误");
				}
				stack.push(res+"");
			}
		}
		
		return Integer.parseInt(stack.pop());

	}

测试是否好用:

public static void main(String[] args) {
		//(3+4)*5-6=29
		String suffixExpression = "3 4 + 5 * 6 -";
		List<String> list = getListString(suffixExpression);

		System.out.println("list;" + list);
		
		int res = calculate(list);
		System.out.println("最终的结果为:"+res);
	}

结果:list;[3, 4, +, 5, *, 6, -]
           最终的结果为:29

 

 

猜你喜欢

转载自blog.csdn.net/we1less/article/details/106163324
今日推荐