数组模拟环形队列

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
 */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ReflectMirroring

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值