栈(stack)是一种FILO(first in last out)先进后出的结构。
举例:一个盒子里依次放入A、B、C、D四块砖,取出的顺序是D、C、B、A。即D最后放入,最先取出。
java 队列(queue)是一种FIFO(first in first out)先进先出的结构。
举例:食堂排队打饭,A、B、C、D依次按序到达,A、B、C、D依次离开。即A最先到达,A最先离开。
简易版的栈,未考虑线程安全问题。
public class StackNew<T> {
Object[] elementData; //数组存储
int index = 0; //实际存储的元素个数,也可作为下标索引
int capacityIncrement = 0;
public StackNew() {
this(10);
}
//默认以两倍方式扩容
public StackNew(int initialCapacity) {
this(initialCapacity, 0);
}
public StackNew(int initialCapacity, int capacityIncrement) {
if (initialCapacity < 0)
throw new IllegalArgumentException("illegal capacity " + initialCapacity);
elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
public void push(Object v) {
ensureCapacity(index + 1);
elementData[index++] = v;
}
//首先进行容量判断,是否需要扩容
private void ensureCapacity(int minCapacity) {
if (minCapacity > elementData.length) {
grow(minCapacity);
}
}
public void grow(int minCapacity) {
int oldCapacity = elementData.length;
//自增值为0,则以2倍的方式扩容
int newCapacity = oldCapacity + (capacityIncrement > 0 ? capacityIncrement : oldCapacity);
if (newCapacity < minCapacity) {
newCapacity = minCapacity;
}
elementData = Arrays.copyOf(elementData, newCapacity);
}
public T pop() {
T obj;
obj = peek(); //取出数组的最后一个元素
removeElementAt(index); //将此元素移除
return obj;
}
private void removeElementAt(int index) {
elementData[index] = null;
}
public T peek() {
if (index == 0) throw new EmptyStackException();
return (T) elementData[--index];
}
public Boolean empty() {
return index == 0;
}
//当前存放了多少元素
public int size() {
return index;
}
//capacity容量,最多能存放多少元素
public int capacity() {
return elementData.length;
}
@Override
public String toString() {
return Arrays.toString(elementData);
}
}