java实现队列的出队和入队

接口类:

/**
 * 〈天道酬勤〉
 *
 * @author wu
 * @create 2019/4/15 21:26
 * MyQueue: enqueue(), dequeue(), isEmpty()
 */
public interface MyQueue {
        //入队
        boolean enqueue(Object obj);
        //出队
        boolean dequeue();
        //判空
        boolean isEmpty();
}

接口实现:

/**
 * 〈天道酬勤〉
 *
 * @author wu
 * @create 2019/4/15 21:37
 */
public class MyQueueImpl implements MyQueue {
    private static final int MAX_CAPACITY = Integer.MAX_VALUE - 8;
    private static final int DEFAULT_CAPACITY = 10;
    private Object[] objs;
    private int front;  //队列头,允许删除
    private int rear;   //队列尾,允许插入

    public MyQueueImpl() {
        this(DEFAULT_CAPACITY);
    }

    public MyQueueImpl(int capacity) {
        if (capacity < 0 || capacity > MAX_CAPACITY) {
            throw new IllegalArgumentException("capacity=" + capacity);
        }
        objs = new Object[capacity];
    }

    @Override
    public boolean enqueue(Object obj) {
        if (rear == objs.length - 1) {
            this.grow();

        } else {
            objs[rear++] = obj;
        }
        return true;
    }

    private void grow() {   //扩容
        objs = Arrays.copyOf(objs, objs.length + (objs.length>>1));
    }

    @Override
    public boolean dequeue() {
        if (isEmpty()) {
            throw new EmptyStackException();
        } else {
            Object ojs = (Object) objs[front];  
            objs[front++] = null;     //释放队列的front端的元素
            return true;
        }
    }

    @Override
    public boolean isEmpty() {
        return rear == front ? true : false;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容