java代码实现自定义栈 + 时间复杂度分析
如果是还不知道栈是啥玩意的同学们请查看我在CSDN写的一篇关于栈的博客:
https://blog.csdn.net/qq_43059674/article/details/86567733
自定义栈java实现代码:
接口定义:
/** * 定义栈接口 * * @author 20190313 * */ public interface Stack<T> { /** * 当前栈是否为空 * @return */ public boolean isEmpty(); /** * 返回当前栈顶元素,但不出栈 * @return */ public T peek() ; /** * 当前栈顶元素出栈 * @return */ public T pop(); /** * 元素入栈 * @param element */ public void push(T element); /** * 返回当前栈中的元素个数 * @return */ public int size(); /** * 清空当前栈 */ public void clear(); }
实现类,底层使用的是数组实现
/** * 实现了定义栈的接口 Stack 该实现类基于数组 属于顺序栈 * @author 20190313 * */ public class ArrayStack<T> implements Stack<T> { private final int DEFAULT_SIZE = 3; private int size = 0; private int capactiy = 0; // top指向下一个能添加元素的位置 private int top = 0; private Object[] array; public ArrayStack() { // TODO Auto-generated constructor stub this.capactiy = this.DEFAULT_SIZE; this.array = new Object[this.capactiy]; } public ArrayStack(int capactiy) { // TODO Auto-generated method stub this.capactiy = capactiy; this.array = new Object[capactiy]; } @Override public boolean isEmpty() { // TODO Auto-generated method stub return size == 0; } @Override public T peek() { // TODO Auto-generated method stub return (T) this.array[this.top - 1]; } @Override public T pop() { // TODO Auto-generated method stub T element = (T) this.array[top - 1]; this.array[top--] = null; this.size--; return element; } @Override public void push(T element) { // TODO Auto-generated method stub if (this.size < this.capactiy) { this.array[top] = element; this.top++; this.size++; } else { enlarge(); push(element); } } /** * 扩容的方法 */ private void enlarge() { this.capactiy = this.capactiy + this.DEFAULT_SIZE; Object[] newArray = new Object[this.capactiy]; System.arraycopy(array, 0, newArray, 0, array.length); // 把旧的array用null填充 Arrays.fill(array, null); this.array = newArray; } @Override public int size() { // TODO Auto-generated method stub return size; } @Override public void clear() { // TODO Auto-generated method stub Arrays.fill(array, null); this.top = 0; this.size = 0; this.capactiy = this.DEFAULT_SIZE; this.array = new Object[this.capactiy]; } }
下面是栈方法的时间复杂度分析
哈,时间复杂度比较简单 除入栈外时间复杂度都为 O(1),下面我们看看入栈的时间复杂度,如果空间足够时间复杂度为O(1),但如果当前容量不足发生扩容那么时间复杂度就为O(n),
也就是说,对于入栈操作来说,最好情况时间复杂度是 O(1),入栈的平均复杂度通关均摊法可以得出为O(1)