欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 数组实现的队列

程序员文章站 2024-03-18 08:07:22
...
/**
 * Java queue
 */
public class QueueX {

    private int[] datas;
    private int front, rear;
    private int mSize;
    private int mItemCount;

    public QueueX(int size) {
        mSize = size;
        datas =  new int[mSize];
        front = 0;
        rear = -1;
        mItemCount = 0;
    }

    /**
     * add item into queue
     * @param e
     */
    public void enque (int e){
        if (mItemCount == mSize) throw new RuntimeException("queue is full, error.");
        if (rear == mSize - 1) rear = -1;
        datas[++rear] = e;
        mItemCount ++;
    }

    /**
     * remove item from queue
     * @return
     */
    public int deque () {
        if (mItemCount < 1) throw new RuntimeException("queue is empty, error.");
        int data = datas[front++];
        if (front == mSize) front = 0;
        mItemCount -- ;
        return data;
    }

    /**
     * check queue front item
     * @return
     */
    public int peek () {
        return datas[front];
    }

    public int getSize () {
        return mItemCount;
    }
    
}