package class01;
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) {
arr = new int[limit];
begin = 0;
end = 0;
size = 0;
this.limit = limit;
}
public void push(int value) {
if (size == limit) {
throw new RuntimeException("队列已满");
}
arr[end] = value;
size++;
end = nextIndex(end);
}
public int pop() {
if (size == 0) {
throw new RuntimeException("队列空了");
}
int ans = arr[begin];
size--;
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());
}
}