栈,先进后出的数据结构(后进先出)

    • pop 弹出一个数据
    • push 压入进栈
    • isEmpty 是否为空

      1. /**
      2. * @author chenshun00@gmail.com
      3. * @since 2021/7/25 10:38 上午
      4. */
      5. public class TestStack<E> {
      6. private Object[] elements;
      7. private int location;
      8. private int initialCapacity = 16;
      9. public TestStack() {
      10. elements = new Object[initialCapacity];
      11. location = 0;
      12. }
      13. public void push(E data) {
      14. checkCapacity();
      15. elements[location] = data;
      16. location = location + 1;
      17. }
      18. @SuppressWarnings("unchecked")
      19. public E pop() {
      20. location = location - 1;
      21. final Object element = elements[location];
      22. elements[location] = null;
      23. return (E) element;
      24. }
      25. public int size() {
      26. return location;
      27. }
      28. private void checkCapacity() {
      29. boolean shouldResize = location / (initialCapacity * 1f) >= 0.75f;
      30. if (shouldResize) {
      31. initialCapacity = initialCapacity << 1;
      32. }
      33. Object[] temp = new Object[this.initialCapacity];
      34. System.arraycopy(elements, 0, temp, 0, location);
      35. elements = temp;
      36. }
      37. public static void main(String[] args) {
      38. TestStack<String> testStack = new TestStack<>();
      39. for (int i = 0; i < 16; i++) {
      40. testStack.push(i + "zz");
      41. }
      42. System.out.println(testStack.size());
      43. System.out.println(testStack.pop());
      44. System.out.println(testStack.pop());
      45. System.out.println(testStack.pop());
      46. System.out.println(testStack.pop());
      47. System.out.println(testStack.size());
      48. }
      49. }