应用:逆波兰表达式(后缀表达式),使用单个栈就行。
package com.linzhongkai.stack;import java.util.LinkedList;import java.util.Scanner;public class CalcPostExp {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);String string = scanner.nextLine();String[] tokens = string.split(" ");System.out.println(calcPostExp(tokens));}public static int calcPostExp(String[] tokens) {LinkedList<Integer> stack = new LinkedList<>();for(String t : tokens) {if (t.equals("+")) {int num1 = stack.removeLast();int num2 = stack.removeLast();stack.addLast(num1+num2);} else if (t.equals("-")) {int num1 = stack.removeLast();int num2 = stack.removeLast();stack.addLast(num2-num1);} else if (t.equals("*")) {int num1 = stack.removeLast();int num2 = stack.removeLast();stack.addLast(num1*num2);} else if (t.equals("/")) {int num1 = stack.removeLast();int num2 = stack.removeLast();stack.addLast(num2/num1);} else {stack.addLast(Integer.valueOf(t));}}if (stack.isEmpty()) {throw new RuntimeException();}return stack.pollLast();}}
