循环队列
循环队列主要注意两点:
- 处理队头与队尾指针的循环移动
front = (front+1)%queueSize
rear = (rear+1)%queueSize - 判断何时队列为空,何时为满
front == rear 时,可能为空,也可能为满,所以要用(rear+1)%queueSize == front 来区分队列为满(当然也可以用(front +1)%queueSize == rear 来区分队列为空)
相关图示
代码实现
CycleQueue 实现类(实际实现中要面向接口编程)
public class CycleQueue {
private Object[] objects;
private int queueSize;
private int front;
private int rear;
public CycleQueue(int queueSize) {
this.queueSize = queueSize;
objects = new Object[queueSize];
}
public boolean push(Object object) {
int tempRear = (rear+1)%queueSize;
if (tempRear == front) {
System.out.println("队列满了");
return false;
}else {
objects[rear] = object;
rear = tempRear;
return true;
}
}
public Object pop() {
if (front == rear) {
System.out.println("队列已为空");
return null;
}else {
Object object = objects[front];
front = (front+1)%queueSize;
return object;
}
}
}
测试类
public class CycleQueueTest {
public static void main(String[] args) {
CycleQueue cycleQueue = new CycleQueue(5);
cycleQueue.pop();
cycleQueue.push(4);
cycleQueue.push("fds");
int a = (int) cycleQueue.pop();
String str = (String) cycleQueue.pop();
System.out.println(a + " " + str);
}
}