数据结构学习(四)----------逆波兰计算器

逆波兰计算器的简单应用

逆波兰表达式的计算 (后缀表达式)

中缀表达式 :(3+4)*5-6

后缀表达式 :“3 4 + 5 * 6 -” 从左向右扫描

前缀表达式 :"- * + 3 4 5 6" 从右向左扫描

将数字入栈,有运算符的话,就从栈中pop出两个元素,计算出结果后将结果再入栈

package com.tmo.stack;

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

/**
 * 
 * @author tmo 逆波兰表达式的计算 (后缀表达式) 中缀表达式 :(3+4)*5-6 后缀表达式 :"3 4 + 5 * 6 -" 从左向右扫描
 *         前缀表达式 :"- * + 3 4 5 6" 从右向左扫描 将数字入栈,有运算符的话,就从栈中pop出两个元素,计算出结果后将结果再入栈
 */
public class NiBoLan {

	public static void main(String[] args) {
		// 定义一个后缀表达式
		String str = "3 4 + 50 * 60 -";

		// 将表达式字符串中的内容放到list中
		ArrayList<String> list = getList(str);
		System.out.println(list);

		int i = calculate(list);
		System.out.println("结果为:"+i);
	}

	// 将后缀表达式放入list集合
	public static ArrayList<String> getList(String str) {

		// 字符串切割
		String[] split = str.split(" ");

		// 将字符串放到list中
		ArrayList<String> list = new ArrayList<String>();

		for (String string : split) {
			list.add(string);
		}
		return list;

	}

	// 计算
	public static int calculate(ArrayList<String> list) {

		// 新建栈
		Stack<String> stack = new Stack<String>();
		// 遍历list
		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; //保存结果
				switch (item) {
				case "+":
					res = num1 + num2;
					break;
				case "-":
					res = num1 - num2;
					break;
				case "*":
					res = num1 * num2;
					break;
				case "/":
					res = num1 / num2;
					break;

				default:
					System.out.println("输入字符有误");
					break;
				}
				//将结果存入栈
				stack.push(""+res);
			}
		}
		//for循环结束后,栈中剩余的就是最终结果
		return Integer.parseInt(stack.pop());
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值