使用数组实现固定长度的队列,原理简析:
代码实现:
package com.isea.brush;
/**
* 使用数组实现长度队列结构
* start:队首,拿取一个数,要存放的位置
* end: 队尾,新加一个元素,应该放在哪个位置,只要end到了数组的长度-1,就回到开头
* size: 队列中的元素的个数
* 用来约束start和end,只要size没有到达数组的长度,就可以在end位置上放数,
* 如果size不等于0,总是把start位置的数,给用户。
*/
public class ArrayQueue {
private Integer[] data;//队列
private Integer start;//队列开始位置
private Integer end;//队列结束位置
private Integer size;//队列容量
public ArrayQueue(int init) {//初始化队列,确定队列空间
if (init < 0) {
throw new IllegalArgumentException("The init is less than 0.....");
}
data = new Integer[init];
start = 0;
end = 0;
size = 0;
}
public Integer peek() {
if (size == 0) {
throw new IllegalArgumentException("The Queue is empty...");
}
return data[start];
}
public void push(int value) {//insert数据
if (size == data.length) {//判断队列是否达到最大容量
throw new IllegalArgumentException("The Queue is full...");
}
data[end] = value;
size++;
// end = (end + 1) % data.length;
end = end == data.length - 1 ? 0 : end + 1;
}
public Integer pop() {
if (size == 0) {//判断队列是否为空
throw new IllegalArgumentException("The Queue is empty....");
}
int result = data[start];
size--;
start = start == data.length - 1 ? 0 : start + 1;
// start = (start + 1) % data.length;
return result;
}
}