用数组结构实现大小固定的队列
分析:
数组队列
这里的数组其实是逻辑上的头尾相连的循环数组,就是循环利用数组
容量固定
其实就是取的指针 start 追着存的指针end跑,可以不设置 size,但是有size判断更方便些,可以把start追着end的逻辑解耦掉。
代码:
package Ashier.arithmetic.my_exercise;
/**
* 用数组结构实现大小固定的队列
*
* @author shierS
* @date 2021/4/2
*/
class ArrayQueue {
Integer[] arr;
Integer size = 0; //队列当前容量
Integer start = 0; //队列当前头部
Integer end = 0; //队列当前尾部
//初始化队列设置容量大小
public ArrayQueue(Integer size) {
if(size < 0){
throw new IllegalArgumentException("The init size is less than 0");
}
arr = new Integer[size];
}
//返回第一个传入的元素,但不删除
public Integer peek() {
if (size == 0) {
return null;
}
return arr[start];
}
//在末尾压入
public void push(int num) {
if (size == arr.length) { //队列满了,不能添加了,抛出异常
throw new ArrayIndexOutOfBoundsException("The queue is full");
}
arr[end] = num; //将元素添加到尾部
size++; //容量++
end = (end == arr.length - 1) ? 0 : end+1;//判断end是否指向了数组末尾,是的化指回到数组头部
}
//弹出头部
public Integer poll() {
if (size == 0) { //队列中空了
throw new ArrayIndexOutOfBoundsException("The queue is empty");
}
size--; //容量--
Integer result = arr[start]; //返回头部元素
start = (start == arr.length - 1) ? 0 : start+1; //移动start标志
return result;
}
}
public class ArrayToQueue {
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(4);
arrayQueue.push(1);
arrayQueue.push(2);
System.out.println(arrayQueue.peek());
System.out.println(arrayQueue.poll());
System.out.println(arrayQueue.peek());
}
}