M87星云

导航

JAVA实现循环队列


/**
* 循环队列
* @param <E>
*/
public class CircleDeQueue<E> {

/**
* 数组容器
*/
private E [] elements;

//尾队列指针
private int rear = 0;

//头队列指针
private int front = 0;

//数组元素个数
private int size = 0;

/**
* 默认容量长度
*/
private int CAPATICY_LENGTH = 10;

/**
* -1 未查询到元素
*/
private static final int ELEMENT_NOT_FOUND = -1;

public CircleDeQueue(){
elements = (E[])new Object[CAPATICY_LENGTH];
}


/**
* 获取元素长度
* @return
*/
public int size(){
return this.size;
}

/**
* 判断数组容器是否为空,空返回true
* @return
*/
public boolean isEmpty(){
return size == 0;
}

/**
* 尾部入队
* @param element
*/
public void enQueueRear(E element){
ensureCapacity(size);
int index = index(size);
elements[index] = element;
rear = index;
size++;
}

/**
* 头部入队
* @param element
*/
public void enQueueFront(E element){
ensureCapacity(size);
front = index(-1);
elements[front] = element;
size++;
}

/**
* 头部出队
* @return
*/
public E deQueueFront(){
if(!isEmpty()){
E element = elements[front];
elements[front] = null;
front = index(1);
size--;
       clear();
       return element;
        }else{
throw new NullPointerException("size: "+size);
}
}

/**
* 尾部出队
* @return
*/
public E deQueueRaer(){
if(!isEmpty()){
E element = elements[rear];
elements[rear] = null;
rear = index(size - 2);
size--;
       clear(); 

return element;
}else{
throw new NullPointerException("size: "+size);
}
}

/**
* 返回队头元素
* @return
*/
public E frontQueue(){
return elements[front];
}

   /**
   * 返回队尾部元素
   * @return
   */
   public E rearQueue(){
   return elements[rear];
   }

    /**
* 清空数据
*/
private void clear(){
if(size == 0){
front = 0;
rear = 0;
elements = (E[]) new Object[DEFAULT_CAPACITY];
}
}

public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("capacity: "+ elements.length);
sb.append(" ,size: "+ size);
sb.append(" ,front: " + front);
sb.append(" ,rear: " + rear);
sb.append("\nCircleQueue"+Arrays.toString(elements));
return sb.toString();
}

/**
* 数组扩容
*/
public void ensureCapacity(int minCapacity){
if(minCapacity >= elements.length){
int length = (elements.length >> 1) + elements.length;
E [] newArr = (E[])new Object[length];
for (int i = 0; i < minCapacity; i++) {
newArr[i] = elements[index(i)] ;
}
front = 0;
rear = minCapacity-1;
elements = newArr;
}
}

/**
* 操作循环队列的下标
* @param index
* @return
*/
private int index(int index){
index += front;
if(index < 0){
return index + elements.length;
}
return index % elements.length;
}

}

posted on 2020-12-31 16:43  挽留匆匆的美丽  阅读(223)  评论(0编辑  收藏  举报