使用固定长度的数组实现队列

/**
 * 固定长度数组实现队列
 */
public class ArrayQueue {
    private int[] data;
    private int start;
    private int end;
    private int size;

    public ArrayQueue(int capacity) {
        if (capacity < 0)
            throw new IllegalArgumentException("capacity should not be less than 0");
        data = new int[capacity];
        start = end = size = 0;
    }

    public void push(int obj) {
        if (size == data.length)
            throw new ArrayIndexOutOfBoundsException("the queue is full");
        data[end] = obj;
        end = (end + 1) % data.length;
        size++;
    }

    public int poll() {
        if (size == 0)
            throw new ArrayIndexOutOfBoundsException("the queue is empty");
        size--;
        int temp = data[start];
        start = (start + 1) % data.length;
        return temp;
    }

    public Integer peek() {
        if (size == 0)
            throw null;
        return data[start];
    }
}

全部评论

相关推荐

很奥的前端仔:如果你接了offer 临时又说不去 hr确实要多做一些工作。 当然如果是接offer之前当我没说
点赞 评论 收藏
分享
11-04 22:56
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务