应用:逆波兰表达式(后缀表达式),使用单个栈就行。

    1. package com.linzhongkai.stack;
    2. import java.util.LinkedList;
    3. import java.util.Scanner;
    4. public class CalcPostExp {
    5. public static void main(String[] args) {
    6. Scanner scanner = new Scanner(System.in);
    7. String string = scanner.nextLine();
    8. String[] tokens = string.split(" ");
    9. System.out.println(calcPostExp(tokens));
    10. }
    11. public static int calcPostExp(String[] tokens) {
    12. LinkedList<Integer> stack = new LinkedList<>();
    13. for(String t : tokens) {
    14. if (t.equals("+")) {
    15. int num1 = stack.removeLast();
    16. int num2 = stack.removeLast();
    17. stack.addLast(num1+num2);
    18. } else if (t.equals("-")) {
    19. int num1 = stack.removeLast();
    20. int num2 = stack.removeLast();
    21. stack.addLast(num2-num1);
    22. } else if (t.equals("*")) {
    23. int num1 = stack.removeLast();
    24. int num2 = stack.removeLast();
    25. stack.addLast(num1*num2);
    26. } else if (t.equals("/")) {
    27. int num1 = stack.removeLast();
    28. int num2 = stack.removeLast();
    29. stack.addLast(num2/num1);
    30. } else {
    31. stack.addLast(Integer.valueOf(t));
    32. }
    33. }
    34. if (stack.isEmpty()) {
    35. throw new RuntimeException();
    36. }
    37. return stack.pollLast();
    38. }
    39. }