用数组实现简单队列
public class ArrayQueue {
//定义一个数组
private int[] quere;
//定义一个队列长度
private int size = 0;
//定义一个首位
private int first = 0;
//定义一个结尾
private int end = -1;
//初始化队列大小
private ArrayQueue() {
}
public ArrayQueue(int size) {
quere = new int[size];
first = 0;
end= -1;
size = 0;
}
public boolean isFull() {
if (size >= quere.length) {
throw new NoSuchElementException("队列已满");
}
return false;
}
public boolean isEmpty(){
return size == 0;
}
//入队
public void enqueue(int data) {
//判断是否已经满了
if (!this.isFull()) {
end = (end + 1) % quere.length;
quere[end] = data;
size++;
}
}
//查看队首
public int peek() {
if (isEmpty()) {
throw new NoSuchElementException("队列为空");
}
return quere[first];
}
//出队
public int dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("队列为空");
}
int val = quere[first];
first = (first + 1) % quere.length;
size--;
return val;
}
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(8);
arrayQueue.enqueue(0);
arrayQueue.enqueue(1);
arrayQueue.enqueue(2);
arrayQueue.enqueue(3);
arrayQueue.enqueue(4);
arrayQueue.enqueue(5);
arrayQueue.enqueue(6);
arrayQueue.enqueue(7);
System.out.println(Arrays.toString(arrayQueue.quere));
System.out.println(arrayQueue.peek());
System.out.println(Arrays.toString(arrayQueue.quere));
System.out.println(arrayQueue.dequeue());
System.out.println(arrayQueue.dequeue());
System.out.println(Arrays.toString(arrayQueue.quere));
arrayQueue.enqueue(8);
arrayQueue.enqueue(9);
System.out.println(Arrays.toString(arrayQueue.quere));
System.out.println(arrayQueue.dequeue());
System.out.println(arrayQueue.dequeue());
System.out.println(Arrays.toString(arrayQueue.quere));
System.out.println(arrayQueue.peek());
arrayQueue.enqueue(10);
arrayQueue.enqueue(11);
arrayQueue.enqueue(12);
System.out.println(Arrays.toString(arrayQueue.quere));
}