[数据结构]-循环队列

循环队列

package com.cn.jichu.day09;

public class LoopQueue<E> {

    /**
     * 数组
     */
    private E[] data;
    /**
     * 头指针,尾指针
     */
    private int head,tail;
    /**
     * 当前数组大小
     */
    private int size;

    public LoopQueue(int size) {
        data = (E[]) new Object[size];
        this.size = size;
    }

    public LoopQueue() {
        this(10);
    }

    /**
     * 入队
     * @param e
     */
    public void enqueue(E e){
        //当尾指针的下一个位置 和头指针重合时,证明当前队列已经满了(当前会浪费一个位置)
        if((tail + 1) % size == head){
            throw new IllegalArgumentException("当前队列满了,不能再加入新的元素了");
        }
        //当前尾指针指向的位置填入新的元素
        data[tail] = e;
        //将指针移动到下一个空位置
        tail = (tail + 1) % size;
    }

    /**
     * 出队
     * @return
     */
    public E dequeue(){
        //当头指针和尾指针重合时,说明队列中没有可取元素
        if(head == tail){
            throw new IllegalArgumentException("当前队列没有元素了");
        }
        E e = data[head];
        data[head] = null;
        head = (head + 1) % size;
        return e;
    }

    @Override
    public String toString(){
        StringBuilder ret = new StringBuilder();
        ret.append("queue  [");
        for(int i=0;i<data.length;i++){
            ret.append(data[i] + " ");
        }
        ret.append(" ] ");
        return ret.toString();
    }



}

猜你喜欢

转载自www.cnblogs.com/anny0404/p/10669349.html