/**
* 队列的改良,使得删除元素的时间复杂度为o1
* @param <E>
*/
public class LoopQueue<E> implements Queue<E>{
private E[] data;
private int front,tail;
private int size;
public LoopQueue(int capacity) {
data = (E[]) new Object[capacity+1];
front = 0;
tail = 0;
size = 0;
}
private void resize(int newCapacity) {
// 要浪费一个空间
E[] newData = (E[]) new Object[newCapacity+1];
// 将 data 要按照顺序放入
for (int i = 0; i < size; i++) {
newData[i] = data[(i+front) % data.length];
}
data = newData;
front = 0;
tail = size;
}
public LoopQueue(){
this(10);
}
@Override
public int getSize() {
return size;
}
@Override
public boolean isEmpty() {
return front == tail;
}
@Override
public void enqueue(E e) {
// 看看队列是否是满的
if ((tail+1) % data.length == front){
// 为什么不直接使用data.length,因为
resize(getCapacity()*2);
}
data[tail] = e;
tail = (tail + 1) % data.length;
size ++;
}
@Override
public E dequeue() {
if (isEmpty()){
throw new IllegalArgumentException("队列为空,无法出队");
}
E ret = data[front];
data[front] = null;
front = (front + 1) % data.length;
if (size == getCapacity() /4 && getCapacity() / 2 !=0){
resize(getCapacity() / 2);
}
return ret;
}
@Override
public E getFront() {
// 判断队列不能为空
if (isEmpty()){
throw new IllegalArgumentException("队列为空");
}
return data[front];
}
public int getCapacity() {
return data.length-1;
}
@Override
public String toString() {
StringBuffer res = new StringBuffer();
res.append(String.format("Queue:size = %d,capacity = %d\n",size,getCapacity()));
res.append("front [");
// 注意这里的界限
for (int i = front; i != tail; i++) {
res.append(data[i]);
res.append(",");
}
res.append("] tail");
return res.toString();
}
}
【数据结构】循环队列
最新推荐文章于 2022-05-18 00:05:38 发布