使用数组手写一个队列

/**
 * 自己实现一个队列
 */
public class MyQueue {
    private int[] objs;

    //队列的头部,获取数据时,总是从头部获取
    private int head;

    //队列的尾部,push数据时,总是从尾部添加
    private int tail;

    //队列的实际长度
    private int size;

    //队列的最大容量
    private int capacity;

    //数组的最大下标
    private int maxIndex;

    public MyQueue(int size) {
        this.capacity = size;
        this.maxIndex = size - 1;
        this.size = 0;
        this.objs = new int[size];
        this.head = this.tail = -1;
    }

    //往队尾添加数据
    public boolean offer(int i) {
        if (size >= capacity) {
            return false;
        }
        if (++tail > maxIndex) {
            tail = 0;
        }
        objs[tail] = i;
        size++;
        return true;
    }

    //从队头拉出数据
    public int poll() {
        Integer i = null;
        if (size <= 0) {
            return i;
        }
        if (++head >= capacity) {
            head = 0;
        }
        size--;
        int temp = objs[head];
        //通过包装类integer将int置空
        objs[head] = i;
        return temp;
    }

    //清空队列
    public void clear() {
        Integer i = null;
        for (int j = 0; j < objs.length; j++) {
            tail = head = -1;
            size = 0;
        }
    }
}

参考博文https://www.cnblogs.com/rainple/p/9988341.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值