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;
}
}
上一篇: java队列的数组实现
下一篇: 二分查找法在算法题的运用