package com.structure.demo; import android.app.Activity; import android.os.Bundle; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.Stack; public class RpnActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rpn); String expression = "3 4 + 5 * 6 -"; int res = calculate(expression); Log.i("tag",res+"最后的结果"); } private int calculate(String expression) { String[] split = expression.split(" "); List<String> list = new ArrayList<>(); for (String element : split) { list.add(element); } //将集合添加到栈中 Stack<String> stack = new Stack<>(); for (String element : list) { //判断是不是数字 if (element.matches("\\d+")) { //是数字直接入栈 stack.push(element); } else { //是符号的话从栈中pop出两个数然后进行运算 int num2 = Integer.parseInt(stack.pop()); int num1 = Integer.parseInt(stack.pop()); int res = 0; if (element.equals("+")) { res = num1 + num2; } else if (element.equals("-")) { res = num1 - num2; }else if (element.equals("*")) { res = num1 * num2; }else if (element.equals("/")) { res = num1 / num2; }else{ throw new RuntimeException("符号不正确"); } stack.push(res+""); } } return Integer.parseInt(stack.pop()); } }
算法和数据结构——后缀表达式(逆波兰表达式)
最新推荐文章于 2022-12-01 21:08:50 发布