栈,先进后出的数据结构(后进先出)
- pop 弹出一个数据
- push 压入进栈
isEmpty 是否为空
/*** @author chenshun00@gmail.com* @since 2021/7/25 10:38 上午*/public class TestStack<E> {private Object[] elements;private int location;private int initialCapacity = 16;public TestStack() {elements = new Object[initialCapacity];location = 0;}public void push(E data) {checkCapacity();elements[location] = data;location = location + 1;}@SuppressWarnings("unchecked")public E pop() {location = location - 1;final Object element = elements[location];elements[location] = null;return (E) element;}public int size() {return location;}private void checkCapacity() {boolean shouldResize = location / (initialCapacity * 1f) >= 0.75f;if (shouldResize) {initialCapacity = initialCapacity << 1;}Object[] temp = new Object[this.initialCapacity];System.arraycopy(elements, 0, temp, 0, location);elements = temp;}public static void main(String[] args) {TestStack<String> testStack = new TestStack<>();for (int i = 0; i < 16; i++) {testStack.push(i + "zz");}System.out.println(testStack.size());System.out.println(testStack.pop());System.out.println(testStack.pop());System.out.println(testStack.pop());System.out.println(testStack.pop());System.out.println(testStack.size());}}
