计算后缀表达式的基本思路是:当遇到一个数时就把它推入栈中;在遇到一个运算符时该运算符就作用于
从该栈弹出的两个数上,将所得结果推入栈中。例如,
常规中缀记法的“3 - 4 + 5”在逆波兰记法中写作“3 4 - 5 +”:先3减去4,再加上5
package com.lemon.stack; public class PostfixExpressionTest { public static void main(String[] args) { //String[] strs={"6","5","2","3"," +","8","*"," +","3"," +","*"}; //String[] strs={"5","1","2","+","4","*","+","3","-"}; //String[] strs={"1","2","3","*","+"}; String[] strs={"1","10","-"}; MyStack stack=new MyStack(); for(int i=0;i<strs.length;i++){ if(strs[i].matches("[0-9]+")){ stack.push(strs[i]); }else if(stack.size()>=2){ Object firstNum= stack.pop(); Object secendNum= stack.pop(); Integer newNum=calculate(Integer.valueOf(secendNum.toString()),Integer.valueOf(firstNum.toString()),strs[i]); stack.push(newNum); }else{ continue; } } while(!stack.isEmpty()){ System.out.println(stack.pop()); } } /** * calculate addition, subtraction,multiplication,division of num1 and num2 * @param num1 * @param num2 * @param operator * @return */ static Integer calculate(Integer num1,Integer num2,String operator){ Integer result=new Integer(0); switch (operator.trim().charAt(0)) { case '+': result=num1+num2; break; case '-': result=num1-num2; break; case '*': result=num1*num2; break; case '/': result=num1/num2; break; default: break; } return result; } }
一个典型应用就是十进制转换二进制,转换的基本思路是:采用"除2取余,逆序排列"法。具体做法是:用2整除十进制整数,可以得到一个商和余数;再用2去除商,又会得到一个商和余数,如此进行,直到商为0时为止,然后把先得到的余数作为二进制数的低位有效位,后得到的余数作为二进制数的高位有效位,依次排列起来。
栈的特点就是后进先出,结合十进制转换二进制的原理,我们可以很轻易的写出如下代码来完成转换工作:
package com.lemon.stack; import java.security.InvalidParameterException; public class BinarySystemConvert { /** * @param args */ public static void main(String[] args) { MyStack<Integer> stack=getBinarySystemNumber(56); while(!stack.isEmpty()){ System.out.println(stack.pop()); } } private static MyStack<Integer> getBinarySystemNumber(Integer num){ MyStack<Integer> result=null; if(num==null){ throw new InvalidParameterException(); } result=new MyStack<Integer>(); while(true){ int quotient=num/2; int remainder=num%2; if(quotient==0){ result.push(new Integer(1)); break; }else{ num=quotient; result.push(new Integer(remainder)); } } return result; } }
运行结果如下: