使用数组简单模拟队列
缺点:无法再次利用已经取出元素的位置,因为front一直向数组末端移动
public class ArrQueue {
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(5);
//测试方法
arrayQueue.addQueue(1);
arrayQueue.addQueue(2);
arrayQueue.addQueue(3);
arrayQueue.showQueue();
System.out.println("----------------------------");
System.out.println(arrayQueue.getQueue());
System.out.println(arrayQueue.headQueue());
arrayQueue.showQueue();
System.out.println("----------------------------");
arrayQueue.addQueue(4);
arrayQueue.addQueue(5);
System.out.println(arrayQueue.isFull());
System.out.println(arrayQueue.addQueue(6));
System.out.println("----------------------------");
System.out.println(arrayQueue.getQueue());
System.out.println(arrayQueue.getQueue());
System.out.println(arrayQueue.getQueue());
System.out.println(arrayQueue.getQueue());
// System.out.println(arrayQueue.getQueue()); //Exception 队列为空,无法删除
System.out.println(arrayQueue.isEmpty());
System.out.println("----------------------------");
}
}
class ArrayQueue {
private int maxSize;//最大容量
private int front;//队头元素的前一个位置
private int rear;//队尾
private int[] arr;//该数组用于存放数据,模拟队列
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
this.front = -1;
this.rear = -1;
this.arr = new int[maxSize];
}
/**
* @return 判断队列是否满
*/
public boolean isFull() {
return rear == maxSize - 1;
}
/**
* @return 判断队列是否为空
*/
public boolean isEmpty() {
return front == rear;
}
/**
* 添加数据到队列
*
* @param n 加入队列的值
* @return 是否添加成功
*/
public boolean addQueue(int n) {
//判断队列是否为满
if (isFull())
return false;
arr[++rear] = n;
return true;
}
/**
* @return 出队列
*/
public int getQueue() {
if (isEmpty())
throw new RuntimeException("队列为空");
return arr[++front];
}
/**
* 显示队列现有元素
*/
public void showQueue() {
if (isEmpty()) {
System.out.println("队列为空");
}
for (int i = front + 1; i <= rear; i++)
System.out.println(arr[i]);
}
/**
* 显示队列头元素
*/
public int headQueue() {
if (isEmpty())
throw new RuntimeException("队列为空");
return arr[front + 1];
}
}