List(vector)实现循环队列中下标变化问题

设计思路

目的:利用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是有顺序性的,中间不存在空元素
如果移出某一元素,后续元素会自动补齐空缺。重新更改下标

所以说,我码的循环队列基本上是寄了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值