栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【数据结构】循环队列

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据结构】循环队列

public class LoopQueue implements Queue{

    private E[] data;
    private int front,tail;
    private int size;


    public LoopQueue(int capacity) {
        data = (E[]) new Object[capacity+1];
        front = 0;
        tail = 0;
        size = 0;
    }


    private void resize(int newCapacity) {
//      要浪费一个空间
        E[] newData = (E[]) new Object[newCapacity+1];
//      将 data 要按照顺序放入
        for (int i = 0; i < size; i++) {
            newData[i] = data[(i+front) % data.length];
        }
        data = newData;
        front = 0;
        tail = size;
    }


    public LoopQueue(){
        this(10);
    }

    @Override
    public int getSize() {
        return size;
    }


    @Override
    public boolean isEmpty() {
        return front == tail;
    }


    @Override
    public void enqueue(E e) {
//        看看队列是否是满的
        if ((tail+1) % data.length == front){
//        为什么不直接使用data.length,因为
            resize(getCapacity()*2);
        }
        data[tail] = e;
        tail = (tail + 1) % data.length;
        size ++;
    }


    @Override
    public E dequeue() {
        if (isEmpty()){
            throw new IllegalArgumentException("队列为空,无法出队");
        }
        E ret = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        if (size == getCapacity() /4 && getCapacity() / 2 !=0){
            resize(getCapacity() / 2);
        }
        return ret;
    }


    @Override
    public E getFront() {
//      判断队列不能为空
        if (isEmpty()){
            throw new IllegalArgumentException("队列为空");
        }
        return data[front];
    }


    public int getCapacity() {
        return data.length-1;
    }


    @Override
    public String toString() {
        StringBuffer res = new StringBuffer();
        res.append(String.format("Queue:size = %d,capacity = %dn",size,getCapacity()));
        res.append("front [");
//      注意这里的界限
        for (int i = front; i != tail; i++) {
            res.append(data[i]);
            res.append(",");
        }
        res.append("] tail");
        return res.toString();
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/763942.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号