Data structure (java) of the queue

Follow the principle of FIFO queue.
1. The implementation of the interface class queue

public interface Queue<E> {

    //获取队列长度
    int getSize();
    //判断队列是否为空
    boolean isEmpty();
    //向队列中添加元素
    void enqueue(E e);
    //从队列中取出元素
    E dequeue();
    //取出队列中的首个元素
    E getFront();

}

2. interface implementation class

public class ArrayQueue<E> implements Queue<E> {

    private Array<E> array;

    public ArrayQueue(int capacity){
        array = new Array<>(capacity);
    }
    public ArrayQueue(){
        array = new Array<>();
    }

    //获取队列长度
    @Override
    public int getSize() {
        return array.getSize();
    }

    //判断队列是否为空
    @Override
    public boolean isEmpty() {
        return array.isEmpty();
    }

    //获取队列容量
    public int getCapacity(){
        return array.getCapacity();
    }

    //向队列中添加元素
    @Override
    public void enqueue(E e) {
        array.addLast(e);
    }

    //从队列中取出元素
    @Override
    public E dequeue() {
        return array.removeFirst();
    }

    //从队列中获取第首个元素
    @Override
    public E getFront() {
        return array.getFirst();
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append("Queue:");
        res.append("front [");
        for(int i = 0 ; i < array.getSize() ; i ++){
            res.append(array.get(i));
            if(i != array.getSize() - 1)
                res.append(", ");
        }
        res.append("] tail");
        return res.toString();
    }

    public static void main(String[] args) {
        //新建队列类
        ArrayQueue<Integer> arrayQueue = new ArrayQueue<Integer>();
        //循环向队列中添加元素
        for (int i=0;i<10;i++){
            arrayQueue.enqueue(i);
            System.out.println(arrayQueue);

            //每添加三个元素从队列中取出一个元素
            if (i % 3==2){
                arrayQueue.dequeue();
                System.out.println(arrayQueue);
            }
        }
    }
}

3. Run the Main method
Here Insert Picture Description
4. The complex array of cohort analysis
Here Insert Picture Description
because the elements removed from the queue, will be the first team out of the elements, the remaining elements of the array are in the queue will be incremented by one position forward, so complexity It is n

Published 35 original articles · won praise 7 · views 2133

Guess you like

Origin blog.csdn.net/weixin_40605573/article/details/90734661