版权声明:Please make the source marked https://blog.csdn.net/qq_31807385/article/details/86484325
题目要求:
如标题
代码分析与实现:
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) {
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;
}
}