接口类:
/**
* 〈天道酬勤〉
*
* @author wu
* @create 2019/4/15 21:26
* MyQueue: enqueue(), dequeue(), isEmpty()
*/
public interface MyQueue {
//入队
boolean enqueue(Object obj);
//出队
boolean dequeue();
//判空
boolean isEmpty();
}
接口实现:
/**
* 〈天道酬勤〉
*
* @author wu
* @create 2019/4/15 21:37
*/
public class MyQueueImpl implements MyQueue {
private static final int MAX_CAPACITY = Integer.MAX_VALUE - 8;
private static final int DEFAULT_CAPACITY = 10;
private Object[] objs;
private int front; //队列头,允许删除
private int rear; //队列尾,允许插入
public MyQueueImpl() {
this(DEFAULT_CAPACITY);
}
public MyQueueImpl(int capacity) {
if (capacity < 0 || capacity > MAX_CAPACITY) {
throw new IllegalArgumentException("capacity=" + capacity);
}
objs = new Object[capacity];
}
@Override
public boolean enqueue(Object obj) {
if (rear == objs.length - 1) {
this.grow();
} else {
objs[rear++] = obj;
}
return true;
}
private void grow() { //扩容
objs = Arrays.copyOf(objs, objs.length + (objs.length>>1));
}
@Override
public boolean dequeue() {
if (isEmpty()) {
throw new EmptyStackException();
} else {
Object ojs = (Object) objs[front];
objs[front++] = null; //释放队列的front端的元素
return true;
}
}
@Override
public boolean isEmpty() {
return rear == front ? true : false;
}
}