package org.example.datastructure.queue;
import java.util.Iterator;
public class ArrayQueueUpgrade<T> implements Queue<T>, Iterable<T> {
private T[] array; //数组
private int head = 0; //头指针
private int tail = 0; //尾指针
public ArrayQueueUpgrade() {
this.array = (T[]) new Object[8];
}
public ArrayQueueUpgrade(int capacity) throws Exception {
if (capacity <= 0) {
throw new Exception("输入不能为负数!");
}
this.array = (T[]) new Object[1 << (int) (Math.log10(capacity - 1) / Math.log10(2)) + 1];
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
int p = head;
@Override
public boolean hasNext() {
return p < tail;
}
@Override
public T next() {
T value = array[p & (array.length - 1)];
p++;
return value;
}
};
}
@Override
public boolean offer(T value) {
if (isFull()) {
resizeExpand();
}
array[tail & (array.length - 1)] = value;
tail++;
return true;
}
@Override
public T poll() {
if (isEmpty()) {
return null;
}
resizeShrink();
T value = array[head & (array.length - 1)];
head++;
return value;
}
@Override
public T peek() {
if (isEmpty()) {
return null;
}
return array[head & (array.length - 1)];
}
@Override
public boolean isEmpty() {
return head == tail;
}
@Override
public boolean isFull() {
return tail - head == array.length;
}
/**
* 修改array数组长度
* 扩容
*/
private void resizeExpand() {
T[] newArray = (T[]) new Object[1 << (int) (Math.log10(2 * array.length - 1) / Math.log10(2)) + 1];
System.arraycopy(array, head & (array.length - 1), newArray, 0, tail - head);
array = newArray;
}
/**
* 修改array数组长度
* 缩容
*/
private void resizeShrink() {
if (tail - head < array.length / 4) {
T[] newArray = (T[]) new Object[1 << (int) (Math.log10(array.length / 2 - 1) / Math.log10(2)) + 1];
System.arraycopy(array, head & (array.length - 1), newArray, 0, tail - head);
array = newArray;
tail = tail - head;
head = 0;
}
}
/**
* 获取队列中元素的个数
*
* @return
*/
public int length() {
return tail - head;
}
}
Java 升级版队列实现
于 2024-01-21 15:00:00 首次发布