/**
* @ClassName: LoopQueue
* @Author: Leo
* @Description: 循環隊列
* @Date: 4/4/2020 4:35 PM
*/
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;
}
public LoopQueue() {
this(10);
}
/**
* 獲取隊列容積
*
* @return
*/
public int getCapacity() {
return data.length - 1;
}
/**
* 獲取隊列元素數量
*
* @return
*/
@Override
public int getSize() {
return size;
}
/**
* 判斷隊列是否爲空
*
* @return
*/
@Override
public boolean isEmpty() {
//首尾引用相等 證明隊列爲空 如果(tail + 1) % data.length == front 則隊列滿
return front == tail;
}
/**
* 入隊
*
* @param e
*/
@Override
public void enqueue(E e) {
//如果隊列滿 則擴容兩倍
if ((tail + 1) % data.length == front) {
resize(getCapacity() * 2);
}
//把元素添加到隊尾
data[tail] = e;
//隊尾指針後移一位
tail = (tail + 1) % data.length;
size++;
}
/**
* 擴容
*
* @param newCapacity
*/
private void resize(int newCapacity) {
//新建一個指定容量的數組
E[] newData = (E[]) new Object[newCapacity + 1];
//把之前數組的元素複製到新數組
for (int i = 0; i < size; i++) {
//偏移量爲front
newData[i] = data[(i + front) % data.length];
}
data = newData;
front = 0;
tail = size;
}
/**
* 出隊
*
* @return
*/
@Override
public E dequeue() {
if (isEmpty()) {
throw new IllegalArgumentException("Cannot dequeue from an empty queue.");
}
//暫存出隊元素
E e = data[front];
data[front] = null;
//頭引用+1
front = (front + 1) % data.length;
size--;
//如果元素數量爲容積的1/4 則縮容爲原來的1/2
if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
resize(getCapacity() / 2);
}
return e;
}
/**
* 獲取隊首元素
*
* @return
*/
@Override
public E getFront() {
if (isEmpty()) {
throw new IllegalArgumentException("Queue is empty.");
}
return data[front];
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append(String.format("Queue: size = %d , capacity = %d\n", size, getCapacity()));
res.append("Front [");
for (int i = front; i != tail; i = (i + 1) % data.length) {
res.append(data[i]);
if ((i + 1) % data.length != tail) {
res.append(", ");
}
}
res.append("] Tail");
return res.toString();
}
}
數據結構之循環隊列[Java]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.