循环队列的入队和出队时间复杂度均为O(1)
package com.wuhongyu.stackAndqueue;
public class LoopQueue<E> implements Queue<E>{
private E[] data;
private int size;
//循环队列的头,尾
private int head,tail;
public LoopQueue(int capacity) {
data = (E[])new Object[capacity+1];
}
public LoopQueue() {
this(10);
}
int getCapacity(){
return data.length-1;
}
@Override
public int getSize() {
return size;
}
@Override
public boolean isEmpty() {
return size==0;
}
//入队
@Override
public void enqueue(E e) {
if(size==data.length-1){
resize(getCapacity()*2);
}
data[tail] = e;
//维护一下尾
tail = (tail+1)%data.length;
size++;
}
private void resize(int capacity) {
E[] newdata = (E[])new Object[capacity+1];
for(int i=0; i<size; i++){
newdata[i] = data[(head+i)%data.length];
}
data = newdata;
head=0;
tail=size;
}
//出队
@Override
public E dequeue() {
if(isEmpty()){
throw new IllegalArgumentException("队列为空");
}
E e = data[head];
data[head] = null;
//维护头
head = (head+1)%data.length;
size--;
if(size==getCapacity()/4 && getCapacity()/2!=0){
resize(getCapacity()/2);
}
return e;
}
@Override
public E getFront() {
if(isEmpty()){
throw new IllegalArgumentException("队列为空");
}
return data[head];
}
}