package day02;
import java.util.linkedList;
import java.util.Queue;
import java.util.Stack;
public class Suan04Queue02 {
public static class MyQueue{
public int[] arr;
public int begin;
public int end;
public int size;
public MyQueue(int limit){
begin = 0;
end = 0;
size = 0;
arr = new int[limit];
}
//判断队列是否满了,满了则不能插入
public void push(int value){
if(size==arr.length){
throw new RuntimeException("队列满了不再加");
}
//没满则可插入,将队列长度+1
size++;
//入队
arr[end] = value;
//入队后将end位置下移,nextIndex的作用就是判断end是否到了数组的最后,若是到了则循环end=0
end = nextIndex(end);
}
//出队是返回并删除数组的begin位置的数
public int poll(){
if(size == 0){
throw new RuntimeException("队列空不能再减");
}
//队列长度减1
size--;
//同理
int temp = arr[begin];
begin = nextIndex(begin);
return temp;
}
public int nextIndex(int end){
if(end == arr.length){
return 0;
}
return (end+1);
}
public static void main(String[] args) {
int oneTestDataNum = 10;
int value = 10;
int testTimes = 10;
for (int i = 0; i < testTimes; i++) {
MyQueue myQueue = new MyQueue(100);
Queue queue = new linkedList<>();
for (int j = 0; j < oneTestDataNum; j++) {
int numq = (int) (Math.random() * value);
if (queue.isEmpty()) {
myQueue.push(numq);
queue.offer(numq);
} else {
if (Math.random() < 0.5) {
myQueue.push(numq);
queue.offer(numq);
} else {
if (myQueue.poll()!=queue.poll()) {
System.out.println("oops!");
}
}
}
}
}
System.out.println("finish!");
}
}
}