java中的栈也是基于数组,和Queue不同的是Stack是后进先出即LIFO: last in first out。可以把栈想象成往箱子里放被子,最后放的被子最先被取出来。

    Stack例子:判断表达式的括号、中括号、大括号的合法性

    1. package com.test;
    2. import java.util.Stack;
    3. /**
    4. * 栈的学习
    5. */
    6. public class StackLearn {
    7. public static void main(String[] args) {
    8. String str = "(<>()}))";
    9. System.out.println(balanced(str));
    10. }
    11. public static boolean balanced(String str) {
    12. Stack<Character> stack = new Stack<>();
    13. char[] array = str.toCharArray();
    14. try {
    15. for (char c : array) {
    16. if (isLeft(c)) {
    17. stack.push(c);
    18. }
    19. if (isRight(c)) {
    20. char tmp = stack.pop();
    21. char left = getLeft(c);
    22. if (tmp != left) {
    23. return false;
    24. }
    25. }
    26. }
    27. } catch (Exception e) {
    28. e.printStackTrace();
    29. return false;
    30. }
    31. return true;
    32. }
    33. public static boolean isLeft(char c) {
    34. return c == '[' || c =='{' || c == '(' || c == '<';
    35. }
    36. public static boolean isRight(char c) {
    37. return c == ']' || c =='}' || c == ')' || c == '>';
    38. }
    39. public static char getLeft(char c) {
    40. char left;
    41. switch (c) {
    42. case ']':
    43. left = '[';
    44. break;
    45. case '}':
    46. left = '{';
    47. break;
    48. case ')':
    49. left = '(';
    50. break;
    51. default:
    52. left = '<';
    53. break;
    54. }
    55. return left;
    56. }
    57. }