设计思路
目的:利用List实现循环队列
首先:
定义循环队列
private Vector<Integer> queue;
private Integer size;
private Integer head; //记录头部下标
private Integer tail; //记录尾部下标
完整代码
public class MyCircularQueue {
private Vector<Integer> queue;
private Integer size;
private Integer head; //记录头部下标
private Integer tail; //记录尾部下标
public MyCircularQueue(int k) {
this.size = k;
this.head = -1;
this.tail = -1;
//初始化列表
this.queue = new Vector<>(this.size);
}
public boolean enQueue(int value) {
//表示队列已满
if (!queue.isEmpty() && Math.abs(tail - head) == 0) {
System.out.println("队列已满");
return false;
}
tail = (++tail) % size;
queue.add(tail, value);
return queue.get(tail) != null;
}
public boolean deQueue() {
//表示队列为空
if (queue.isEmpty()) {
System.out.println("队列为空");
head = -1;
tail = -1;
return false;
}
//队列头出站
head = (++head) % size;
this.queue.removeElementAt(head);
return queue.get(head) == null;
}
public int Front() {
if (isEmpty()) {
return -1;
}
int value = queue.get(tail);
tail = (--tail) % size;
return value;
}
public int Rear() {
//尾部出队列
if (isEmpty()) {
return -1;
}
int value = queue.get(head);
head = (++head) % size;
return value;
}
public boolean isEmpty() {
return queue.isEmpty();
}
public boolean isFull() {
return ((tail + 1) % size) == head;
}
启动
public static void main(String[] args) {
MyCircularQueue test = new MyCircularQueue(5);
test.enQueue(5);
test.enQueue(7);
test.enQueue(4);
test.enQueue(2);
test.enQueue(1);
boolean b;
b = test.deQueue(); //这里打一个断点
b = test.deQueue();
b = test.deQueue();
test.enQueue(1);
test.enQueue(2);
test.enQueue(3);
test.enQueue(4);
}
进入断点
注意! 删除前的集合是这样的
此时的头节点下标为0
删除一个后
很正常,把头节点的元素删除掉,对吧。
队列的原则就是 先进先出。
但是仔细看
我们明明是删除下标为0的元素,可是删除之后,所有元素都向前移动了一位。
所以说List有一个特点就是 不存在不连接的元素,它们一定是顺序的
结论
List是有顺序性的,中间不存在空元素
如果移出某一元素,后续元素会自动补齐空缺。重新更改下标
所以说,我码的循环队列基本上是寄了