java数据结构之表达式计算

import java.util.Stack;
public class 栈的表达式计算 {
	public static void main(String[] args) {
		Stack<Integer> number = new Stack<Integer>();
		Stack<Character> fuhao = new Stack<Character>();
		String ex = "77*2+3+4+10/5";
		int index = 0;
		int num1 = 0;
		int num2 = 0;
		char c = ' ';
		while (true) {
			// 字符
			char op = ex.charAt(index);
			if (isoper(op) == true) {
				//符号栈不为空
				if (!fuhao.isEmpty()) {
					//如果当前运算符的优先级小于或等于运算符中的优先级,则从符号栈中
					//取出一个运算符,再从数栈中弹出两个数进行计算,并将计算后的结果,再压入数栈
					if (youxianji(op) <= youxianji(fuhao.peek())) {
						num2 = number.pop();
						num1 = number.pop();
						c = fuhao.pop();
						number.push(cul(num1, num2, c));
						fuhao.push(op);
					} else {
						//符号栈为空,直接入栈
						fuhao.push(op);
					}
				} else {
					//如果当前运算符的优先级大于运算符中的优先级,直接入栈
					fuhao.push(op);
				}
				index ++;
			}

			// 数字
			else {
				String num = "";
				//解决数字是多位数的情况
				while (!isoper((ex.charAt(index)))) {
					num = num + (ex.charAt(index)-48);
					index = index + 1;
					//为了处理表达式最末尾的情况,到末尾后已经没有操作数了,终止循环
					if (index>=ex.length()) {
						break;
					}
				}
				//数字入栈
				number.push(Integer.parseInt(num));
			}
			if (index>=ex.length()) {
				break;
			}
		}
		while(true){
			if (fuhao.isEmpty()) {
				break;
			} else {
				num2 = number.pop();
				num1 = number.pop();
				c = fuhao.pop();
				number.push(cul(num1, num2, c));
			}
		}
		System.out.println(number.peek());
	}

	public static boolean isoper(int i) {
		if (i == '+' || i == '-' || i == '*' || i == '/') {
			return true;
		} else {
			return false;
		}
	}

	// 判断优先级
	public static int youxianji(char c) {
		if (c == '*' || c == '/') {
			return 1;
		} else if (c == '+' || c == '-') {
			return 0;
		} else {
			return -1;
		}
	}

	public static int cul(int num1, int num2, char c) {
		int res = 0;
		switch (c) {
		case '+':
			res = num1 + num2;
			break;
		case '-':
			res = num1 - num2;
			break;
		case '*':
			res = num1 * num2;
			break;
		case '/':
			res = num1 / num2;
			break;
		default:
			break;
		}
		return res;
	}
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值