/*
利用数组实现队列,对队列中值进行增加查询
*/
public class TestQueue01 {
public static void main(String[] args) {
//演示代码
ArrayQueue arrayQueue = new ArrayQueue();
arrayQueue.iniQueue(3);
arrayQueue.addQueue(4);
arrayQueue.addQueue(5);
arrayQueue.addQueue(6);
arrayQueue.showQueue();
arrayQueue.addQueue(7);
arrayQueue.getQueue();
arrayQueue.showQueue();
}
}
//初始化队列
class ArrayQueue {
int arr[];
int maxSize;
int front;
int rear;
//初始化数组
public void iniQueue(int length) {
arr = new int[length];
maxSize = arr.length;//找到数列的最大长度
front = -1;//指向队列头的前一个位置
rear = -1; //定义初始的尾指针
}
public boolean isFull() { //判断数组是否满
return maxSize - 1 == rear;
}
public boolean isEmpty(){//判断数组是否为空
return rear == front;
}
// 向数组中加入数据
public void addQueue(int element) {
if (isFull()) {
System.out.println("已满,放入失败");
return;
}
rear++;//指针后移动
arr[rear] = element;
}
//从数组中取出数据
public int getQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空 无法取出");
}
front++; //front后移
int temp = arr[front];
arr[front] = 0;//恢复默认值
return temp;
}
//用于显示的输出队列
public void showQueue(){
String s = Arrays.toString(arr);
System.out.println(s);
}
}
这种队列的缺点是容易造成假溢出,队列并没有真正的满.