集册 Java实例教程 非通用出列

非通用出列

欢马劈雪     最近更新时间:2020-01-02 10:19:05

567
非通用出列

package com.company.stucts.queue;


import java.util.Arrays;
/** N  o w  J a v a . c o m 提 供 **/

/**

 * Double ended queue

 */

@SuppressWarnings({ "Duplicates", "WeakerAccess" })

public class Dequeue {

    private final Object[] data;

    private int head, tail, size;


    public Dequeue(int size) {

        data = new Object[size + 1];

        head = tail = 0;

        this.size = size;

    }/**来自 nowjava - 时代Java**/


    public void pushFirst(Object o) {

        if (size() == size) {

            throw new IllegalStateException("Queue is full");

        }


        head = (--head + data.length) % data.length;

        data[head] = o;

    }


    public Object popFirst() {

        if (isEmpty()) {

            throw new IllegalStateException("Queue is empty");

        }


        Object o = data[head];

        data[head] = null;

        head = ++head % data.length;

        return o;

    }


    public void pushLast(Object o) {

        if (size() == size) {

            throw new IllegalStateException("Queue is full");

        }


        data[tail] = o;

        tail = ++tail % data.length;

    }


    public Object popLast() {

        if (isEmpty()) {

            throw new IllegalStateException("Queue is empty");

        }

        Object o = data[tail];

        data[tail] = null;

        tail = (--tail + data.length) % data.length;

        return o;

    }


    public boolean isEmpty() {

        return head == tail;

    }


    public int size() {

        if (head > tail) {

            return data.length - head + tail;

        } else {

            return tail - head;

        }

    }


    @Override

    public String toString() {

        return "Queue: " + "\n" + "data[]: " + Arrays.toString(data) + "\n"

                + "data[] length: " + data.length + "\n" + "size: "

      
展开阅读全文