废话不多说,直接上代码。
/**
* @author lizz
* @ClassName MyQueue.java
* @Description 用数组实现 循环队列
* @createTime 2022年04月13日 09:39:00
* 队尾指针指向的位置永远空出1位,所以队列最大容量是数字长度减1。
* (队尾下标-1) % 数组长度 = 队头下标 表示队列已经满了
*/
public class MyQueue {
/**
* 定义一个数组来存放数据
*/
private String[] objectArray;
/**
* 队头下标
*/
private int front;
/**
* 队尾下标
*/
private int rear;
/**
* 使用时初始化队列长度
* @param capacity
*/
public MyQueue(int capacity) {
this.objectArray = new String[capacity];
}
/**
* 入队
* @param element 入队的元素
* @throws Exception
*/
public void enQueue(String element) throws Exception {
if((rear+1)%objectArray.length == front){
throw new Exception("队列已满!");
}
objectArray[rear] = element;
rear = (rear+1) % objectArray.length;
}
/**
* 出队
* @return 队列中的数据
* @throws Exception
*/
public Object deQueue() throws Exception {
if(rear == front){
throw new Exception("队列已空!");
}
Object deQueueElement = objectArray[front];
front = (front+1) % objectArray.length;
return deQueueElement;
}
/**
* 输出队列
*/
public void output(){
for (int i = front; i != rear ; i = (i+1)% objectArray.length) {
System.out.println(objectArray[i]);
}
System.out.println("-------------------------------");
}
public static void main(String[] args) throws Exception {
MyQueue myQueue = new MyQueue(4);
myQueue.enQueue("test1");
myQueue.enQueue("test2");
myQueue.enQueue("test3");
myQueue.output();
myQueue.deQueue();
myQueue.output();
myQueue.enQueue("test4");
myQueue.output();
myQueue.enQueue("test5");
myQueue.output();
}
}