Java实现循环队列(顺序存储结构)

队列 满的条件是 (nextIndex +1) % capacity==firstIndex;
队列为空的条件是firIndex==nextIndex;
数组总是会空一个元素以满足上面两个条件;好处是提取元素和追加元素的复杂度都是O(1);
package com.myTest.queue;

import java.util.concurrent.locks.ReentrantLock;

public class CurrentArrayQueue<E> {
    public static void main(String[] args) {

        CurrentArrayQueue<Integer> queue = new CurrentArrayQueue<>(5);
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        queue.offer(4);
        queue.poll();
        queue.offer(5);
        queue.poll();
        queue.offer(6);
        queue.poll();
        queue.offer(7);
        queue.poll();
        queue.offer(10);
        System.out.println(queue);
    }

    private static ReentrantLock lock;
    //队列头元素所在的索引
    private static int firstIndex;
    //队列的下一个元素的索引,默认 firstIndex==nextIndex 则为empty;
    private static int nextIndex;
    //初始化数组大小
    private static int capacity;
    private static Object[] elements;

    public CurrentArrayQueue(int capacity) {
        lock = new ReentrantLock();
        firstIndex=0;
        nextIndex=0;
        elements=new Object[capacity];
        this.capacity=capacity;
    }

    /**
     * 追加元素
     * @param e
     * @return
     */
    public Boolean offer(E e){
        if(e==null){
            throw new NullPointerException();
        }
        if((nextIndex+1)%capacity==firstIndex){
            throw new ArrayIndexOutOfBoundsException();
        }
        lock.lock();
        try{
            if((nextIndex+1)%capacity!=firstIndex){
                //如果队列没有满
                elements[nextIndex]=e;
                nextIndex=(nextIndex+1)%capacity;
            }
        }finally {
            lock.unlock();
        }

        return true;
    }

    /**
     * 检索并删除头元素
     */
    public E poll(){
        if(firstIndex==nextIndex){
            return null;
        }
        lock.lock();
        E element=null;
        try{
             element = (E)elements[firstIndex];
            elements[firstIndex]=null;
            firstIndex=(firstIndex+1)%capacity;
        }finally {
            lock.unlock();
        }

        return element;
    }
    @Override
    public String toString() {
        String result="[";
        for (Object object:elements) {
            result=result+","+object;
        }
        result=result.replaceFirst(",","");
        result=result+"]";
        return result;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值