队列中添加数据、取出数据,访问队头元素、判断队列是否为空、判断队列是否满了
public class MyQueue {
private long[] arr;
// 有效数据大小
private int elements;
// 对头
private int front;
// 队尾
private int end;
// 无参构造
public MyQueue() {
arr = new long[10];
elements = 0;
front = 0;
end = -1;
}
// 有参构造,参数为数组大小
public MyQueue(int maxsize) {
arr = new long[maxsize];
elements = 0;
front = 0;
end = -1;
}
/*
* 添加数据,从队尾插入
*/
public void insert(long value) {
if (end == arr.length - 1) {
end = -1;
}
arr[++end] = value;
elements++;
}
/*
* 删除数据,从对头删除
*/
public long remove() {
long value = arr[front++];
if (front == arr.length) {
front = 0;
}
elements--;
return value;
}
/*
* 查看对头数据
*/
public long peek() {
return arr[front];
}
/*
* 返回队列中有效元素个数
*/
public int size() {
return elements;
}
/*
* 判断队列是否为空
*/
public boolean isEmpty() {
return elements == 0;
}
/*
* 判断队列是否满了
*/
public boolean ifFull() {
return elements == arr.length;
}
}
写一个测试类
public class TestMyQueue {
public static void main(String[] args) {
MyQueue myQueue = new MyQueue(5);
//添加数据
myQueue.insert(99);
myQueue.insert(77);
myQueue.insert(33);
myQueue.insert(22);
myQueue.insert(11);
//查看对头数据
System.out.println("对头数据:"+myQueue.peek());
//有效元素个数
System.out.println("有效元素个数:"+myQueue.size());
//判断是否满了
System.out.println("是否满了:"+myQueue.ifFull());
//取出数据,先判断是否为空再打印
while (!myQueue.isEmpty()) {
System.out.print(myQueue.remove()+" ");
}
}
}
运行结果