数组模拟队列
队列的特性是先进先出。主要的应用是作为缓冲池。
首先要有maxSize用来记录队列的最大长度。并且记录front和rear。
rear表示队列中的最后一个元素,front表示队列中的第一个元素,在起始时,队列中没有数据。所以初始化front和rear都为-1.
判断队列是否为空的条件是front==rear;
判断队列是否满的条件是rear==maxSize -1;
所以push表示添加数据。首先要判断队列是否已经满了,如果没有就先把front++。然后将该值加入到数组的索引为front的位置。
pop表示弹出一个元素。首先要判断队列是否为空,如果没有就先把rear++。
使用数组模拟队列会有很多的问题,如假溢出现象。此时我们需要考虑循环队列。
class ArrayQueue{
private int maxSize;
private int front = -1;
private int rear = -1;
private int[] arr;
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[this.maxSize];
}
public boolean isEmpty()
{
return rear == front;
}
public boolean isFull()
{
return rear == maxSize-1;
}
public void pop(int n)
{
if (isFull())
{
System.out.println("队列已满");
return;
}
else
{
arr[++rear] = n;
}
}
public int push()
{
if (isEmpty())
{
throw new RuntimeException("没有数据");
}
return arr[++front];
}
public void show()
{
if (isEmpty())
{
System.out.println("没有数据");
}
for (int i = 0; i < arr.length; i++) {
System.out.print(String.format("a[%d] = %d ",i,arr[i] ));
}
}
//查看队列的头数据
public int peek()
{
if (isEmpty())
{
throw new RuntimeException("没有数据");
}
return arr[front+1];
}
}
数组模拟环形队列
public class CircleQueue {
/*
front指向队列中的第一个元素。初始值为0
rear指向队列中最后一个元素的后一个位置,初始值为0,希望流出一个空间作为约束
队列满的条件:(rear+1)%maxsize == front
队列为空的条件:rear == front
数组中有效元素的个数(rear-front+maxsize)%maxsize
*/
private int maxSize;
private int front = 0;
private int rear = 0;
private int[] arr;
public CircleQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[this.maxSize];
}
public boolean isEmpty()
{
return rear == front;
}
public boolean isFull()
{
return (rear+1)%maxSize == front;
}
public void pop(int n)
{
if (isFull())
{
System.out.println("队列已满");
return;
}
else
{
arr[rear] = n;
rear = (rear+1)%maxSize;
}
}
public int push()
{
if (isEmpty())
{
throw new RuntimeException("没有数据");
}
int temp = arr[front];
front = (front+1)%maxSize;
return temp;
}
public int size()
{
return (rear-front+maxSize)%maxSize;
}
public void show()
{
if (isEmpty())
{
System.out.println("没有数据");
}
for (int i = front; i < front + (rear-front+maxSize)%maxSize; i++) {
System.out.print(String.format("a[%d] = %d ",i%maxSize,arr[i%maxSize]));
}
}
public int peek()
{
if (isEmpty())
{
throw new RuntimeException("没有数据");
}
return arr[front];
}
}
使用LinkedList模拟队列
Java中存在LinkedList。而LinkedList中有getFirst和getLast方法。以及removeFirst和removeLast。
可以直接创建要给LinekdList来模拟队列。更加方便,也更加简单。