队列
特殊线性表,只允许在 front 表的前端进行 删除操作, 在表的后端rear进行插入操作。
就是所谓的 先进先出。
分为 顺序队列 和 循环队列
顺序队列
一个连续空间
两个指针管理: 一个头指针,一个尾指针。
假溢出和真溢出
假溢出
真溢出
关注点:
添加元素的时候,front指针。
删除元素的时候,rear指针。
判断什么时候是空队列:
代码
package queue;
public class ArrayQueue {
private int[] array;
private int maxSize;
private int frontPoint;
private int rearPoint;
public ArrayQueue(int maxSize){
this.maxSize = maxSize;
array = new int[maxSize];
frontPoint = -1;
rearPoint = -1;
}
// whether the current queue is full
// 判断当前队列 是否 满了
public boolean isFull(){
return rearPoint == maxSize - 1;
}
// whether the current queue is empty
// 判断当前队列 是否 空
public boolean isEmpty(){
return rearPoint == frontPoint;
}
// add element into queue
// 添加元素
public void add(int n){
if (isFull()){
System.out.println("the queue is already full!");
return;
}
rearPoint++;
array[rearPoint] = n;
}
// delete element from queue
// 获取元素
public int get(){
if (isEmpty()){
throw new RuntimeException("Empty queue!");
}
frontPoint ++;
return array[frontPoint];
}
// showing each element in queue
// 查看队列中的元素
public void findQueue(){
if (isEmpty()){
throw new RuntimeException("Empty queue!");
}
int index = 0;
for(int i = frontPoint + 1; i < array.length; i++){
System.out.printf("array[%d] = %d\n",index,array[i]);
index += 1;
}
}
// showing the first front element
public int frontQueue(){
if (isEmpty()){
throw new RuntimeException("Empty queue!");
}
return array[frontPoint + 1];
}
}
测试
package queue;
public class TestApp {
public static void main(String[] args) {
//
// 创建队列
ArrayQueue arrayQueue = new ArrayQueue(5);
// 添加元素
arrayQueue.add(1);
arrayQueue.add(2);
arrayQueue.add(3);
arrayQueue.add(4);
arrayQueue.add(5);
// arrayQueue.findQueue();
// 取出第一个元素
arrayQueue.get();
arrayQueue.get();
// 查看队列内的元素
arrayQueue.findQueue();
// 查看队列第一个元素
System.out.println(arrayQueue.frontQueue());
}
}