环形队列 - java实现

本文介绍了一个基于数组实现的循环队列结构,包括基本的操作如push、pop和peek等,并提供了完整的Java代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class LoopQueue {
    private byte[] _buf;
    private int _head;
    private int _tail;
    private int _size;
    private int _capacity;

    public LoopQueue(int capacity){
        _capacity = capacity;
        _buf = new byte[_capacity];
        _head = 0;
        _tail = 0;
        _size = 0;
    }
//将len长的buf加入到lp中
    public boolean push(byte[] buf, int len){
        if(this._size+len>this._capacity){
            Public.mylog.d(LOG_TAG,"_buf is over flow");
            return false;
        }

    for (int i = 0; i < len; i++) {
        _buf[(_tail + i) % _capacity] = buf[i];
    }
        _tail = (_tail+len)%_capacity;
        _size +=len;

        return true;
    }
//消费掉len长的数据
    public boolean pop(int len){
        if(_size<len){
            Public.mylog.d(LOG_TAG,"loopQueue demanding more than exists");
            return false;
        }
        _head = (_head+len)%_capacity;
        _size -=len;

        return true;
    }
//查看从head开始的len长度的内容,把这些内容放到buf里面
    public boolean peek(byte[] buf, int len){
        if(_size<len){
            Public.mylog.d(LOG_TAG,"loopQueue demanding more than exists");
            return false;
        }

        for(int i=0;i<len;i++){
            buf[i]=_buf[(_head+i)%_capacity];
        }

        return true;
    }
//判断是不是满了
    public boolean isfull(){
        return (_capacity == _size);
    }
//判断是不是空的
    public boolean isempty(){
        return (_size==0);
    }
//总的大小
    public int capacity(){
        return _capacity;
    }
//当前数据量
    public int size(){
        return _size;
    }
//clear all data
    public void clear(){
        _tail = _head;
        _size = 0;
    }

    public int read(byte[] buf){
        int size = size();
        size = Math.min(size,buf.length);
        if(size>0) {
            peek(buf, size);
            pop(size);
            return size;
        }else
            return 0;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值