package class01;
/**
* @author chencc
* @Description 数组实现队列
* @Date 2022/3/16 13:50
*/
public class RingArray {
//构建一个队列(内部实现是数组)
public static class MyQueue {
private int[] arr;
private int begin;
private int end;
private int size;
private final int limit;
//构造器(初始化)
public MyQueue(int limit) {
//初始化limit大小的空数组
arr = new int[limit];
//开始指针
begin = 0;
//结尾指针
end = 0;
//数组大小
size = 0;
this.limit = limit;
}
//插入数据
public void push(int value) {
//判断数组是否满了
if (size == limit) {
throw new RuntimeException("队列已满");
}
//将当前数加入到数组end位置
arr[end] = value;
//数组大小+1
size++;
//判断end的指针位置
end = nextIndex(end);
}
//弹出数据
public int pop() {
if (size == 0) {
throw new RuntimeException("队列空了");
}
//取出数组begin职位的数
int ans = arr[begin];
//数组大小-1
size--;
//判断begin的指针位置
begin = nextIndex(begin);
return ans;
}
private int nextIndex(int i) {
return i < limit - 1 ? i + 1 : 0;
}
}
public static void main(String[] args) {
MyQueue queue = new MyQueue(5);
queue.push(3);
queue.push(2);
queue.push(1);
queue.push(4);
queue.push(8);
System.out.println("=====================");
System.out.println(queue.pop());
}
}
数组实现队列
最新推荐文章于 2023-12-28 18:29:16 发布