public class RoundQueue {
private String[] items;
private int n;
private int front;
private int rear;
public RoundQueue(int capacity) {
this.items = new String[n];
this.n = capacity;
this.front = 0;
this.rear = 0;
}
public boolean enqueue(String item) {
if ((rear + 1) % n == front) {
System.out.println("队列已满");
return false;
}
items[rear] = item;
rear = (rear + 1) % n;
return true;
}
public String dequeue() {
if (front == rear) {
System.out.println("队列为空");
return null;
}
String result = items[front];
front = (front + 1) % n;
return result;
}
public void printAll() {
if (0 == n) return;
for (int i = front; i % n != rear; i = (i + 1) % n) {
System.out.print(items[i] + " ");
}
System.out.println();
}
}
写对循环队列代码的关键就在于队空和队满的判断,技巧可以参看我的另一篇博客:
如何判断循环队列为队空or队满? 里面还有循环队列的其他实现思路。