先入后出的有序列表。可以使用数组模拟,需要数组maxSize,数组,还有表示栈顶的指针。
    应用:计算中缀表达式。需要两个栈。一个数字栈一个符号栈。

    1. package com.linzhongkai.stack;
    2. import java.util.LinkedList;
    3. public class CalcMidExp {
    4. public static void main(String[] args) {
    5. String str = "1+2*3+3/5-1";
    6. System.out.println(calcMidExp(str));
    7. }
    8. public static int calcMidExp(String str) {
    9. int res = 0;
    10. LinkedList<Integer> stackNum = new LinkedList<>();
    11. LinkedList<Character> stackChar = new LinkedList<>();
    12. char[] chars = str.toCharArray();
    13. for(char ch : chars) {
    14. //如果是数字
    15. if (Character.isDigit(ch)) {
    16. if (!stackChar.isEmpty()) {
    17. if (stackChar.getLast() == '*' ) {
    18. int num1 = ch-'0';
    19. int num2 = stackNum.removeLast();
    20. int chengfa = num1 * num2;
    21. stackNum.addLast(chengfa);
    22. stackChar.removeLast();
    23. } else if (stackChar.getLast() == '/') {
    24. int num1 = ch-'0';
    25. int num2 = stackNum.removeLast();
    26. int chufa = num2 / num1;
    27. stackNum.addLast(chufa);
    28. stackChar.removeLast();
    29. } else {
    30. stackNum.addLast(ch-'0'); //转换为数字
    31. }
    32. } else {
    33. stackNum.addLast(ch-'0'); //转换为数字
    34. }
    35. } else {
    36. stackChar.addLast(ch);
    37. }
    38. }
    39. while (!stackChar.isEmpty()) {
    40. char fuhao = stackChar.removeLast();
    41. if (fuhao == '+') {
    42. int num1 = stackNum.removeLast();
    43. int num2 = stackNum.removeLast();
    44. int jiafa = num1+num2;
    45. stackNum.addLast(jiafa);
    46. }
    47. if (fuhao == '-') {
    48. int num1 = stackNum.removeLast();
    49. int num2 = stackNum.removeLast();
    50. int jianfa = num2-num1;
    51. stackNum.addLast(jianfa);
    52. }
    53. }
    54. res = stackNum.getFirst();
    55. return res;
    56. }
    57. }