package com.pp; import java.util.Arrays; /** * 栈 */ public class MyStack<E> { private Object[] stack; int top = -1; public MyStack() { this.stack = new Object[10]; } /** * 判断是否为空 * @return */ public boolean isEmpty(){ return top==0; } /** * 压栈 */ public E push(E item){ stack[++top] = item; return item; } /** * 弹栈 永远弹栈顶元素 */ public E peek(){ if (this.isEmpty()){ return null; } return (E) stack[top]; } /** * 出栈 出栈栈顶 */ public E pop(){ E e = this.peek(); stack[top--] = null; return e; } /** * 栈满 需要扩容 */ public void ensureCapcity(int size){ int length = stack.length; if (size>length){ int newlen = size; Arrays.copyOf(stack,newlen); } } /** * 返回顶元素 * @return */ public E getTop(){ if (this.isEmpty()){ return null; } return (E) stack[top]; } }
package com.pp; public class StackTest { public static void main(String[] args) { MyStack<Integer> integerMyStack = new MyStack<>(); integerMyStack.push(1); integerMyStack.push(2); integerMyStack.push(3); integerMyStack.push(4); integerMyStack.push(5); integerMyStack.pop(); integerMyStack.pop(); Integer top = integerMyStack.getTop(); System.out.println(top); } }