package queue;

/*
* 数组模拟环形队列
*/
public class Queue
{
/*
* 先进行分析:
* 队列必须有的东西:
* 表示队头的front指针,
* 表示队尾的rear指针
* 这个队列存放数据的数组对象
* 表示这个队列大小的size
*
* 方法有:
* 加入新的元素进队列
* 删除元素
* 判断队列是否为空(采取front==rear)的方法
* 判断队列是否满了(采取((front+1)%size)==rear的方法
* 显示队列保存的所有数据
*
*/
public int front;
public int rear;
public int[] arr;
public int size;

public Queue(int size)
{
this.size=size;
arr=new int[size];
}
public void add(int element)
{
if(!this.Isfull())
{
arr[rear]=element;
rear=(rear+1)%size;
}
else
{
System.out.println("the queue is full");
}
}
public int remove() throws Exception
{
if(Isempty())
{
throw new Exception("there is nothing in the queue");
}
int temp=arr[front];
front=(front+1)%size;
return temp;
}
public boolean Isempty()
{
return rear==front;
}
public boolean Isfull()
{
return ((rear+1)%size)==front;
}
/*
* 这里是显示队列里面的元素,
* 队列里面的元素个数是(rear-front+size)%size
*/
public void show()
{
if(Isempty())
{
System.out.println("there is nothing in the queue");
return;
}
for (int i = front; i < (rear-front+size)%size+front; i++)
{
System.out.print(arr[i%size]+" ");
}
System.out.println();
}
public static void main(String[] args)
{

}
}
/*
* 编写循环队列的实现方法有多种
* 1: 最常见简单的就是上面的方法,空出一个数组空间进行判断
* 为空:front==rear
* 为满:(rear+1)%size==front
* 2: 就是不浪费一个空间,这里采取的是增加一个标记flag,
* 当入队列时,flag=true,当出队列时flag=false,
* 为空:front==rear&&flag==false
* 为满:front==rear&&flag==true
* 3. 也不浪费一个空间,就是增加一个表示队列现在元素个数的count
* 为空:count==size
* 为满:count==0
*/