环形队列

环形队列

队列:先进先出,类似于排队服务,先来的人排在前面,后来的人排在后面,按照排队顺序享受服务;

PS:但是队列只能用一次,可以优化成环形队列重复使用空间

  1. 变量front:指向环形队列的头部;
  2. 变量rear:指向环形队列尾部的后一个位置;
  3. 变量maxSize:环形队列长度;
  4. 环形队列为空:front = rear
  5. 环形队列为满:(rear + 1)% maxSize = front
  6. 环形队列已利用的空间:(rear + maxSize - front)% maxSize
class CircleQueue
{
	private int front;	//指向环形数组的头部
	private int rear;	//指向环形数组尾部的后一个位置
	private int [] arr;	//用数组模拟环形队列
	private int maxSize;	//数组长度
	public CircleQueue(int arrLen)	//构造函数
	{
		this.maxSize = arrLen;
		this.arr = new int [arrLen];
	}
	public boolean isEmpty()	//判断环形队列是否为空
	{
		return front == rear;
	}
	public boolean isFull()	//判断环形队列是否为满
	{
		return (rear + 1) % maxSize == front;
	}
	public int size()	//返回环形队列已利用的空间
	{
		return (rear + maxSize - front) % maxSize;
	}
	public void addQueue(int num)	//入队
	{
		if (isFull())
		{
			throw new RuntimeException("循环队列已满,不能继续添加数据!");
		}
		else
		{
			arr[rear] = num;
			rear = (rear + 1) % maxSize;
		}
	}
	public int getQueue()	//出队
	{
		if (isEmpty())
		{
			throw new RuntimeException("循环队列已空,不能继续删除数据");
		}
		else
		{
			int value = arr[front];
			front = (front + 1) % maxSize;
			return value;
		}
	}
	public void showQueue()	//查看环形队列里面所有的值
	{
		if (isEmpty())
		{
			throw new RuntimeException("循环队列已空,没有任何数据");
		}
		else
		{
			int sum = front + size();
			for (int i = front; i < sum; i++)
			{
				System.out.printf("arr[%d] = %d\n", i % maxSize, arr[i % maxSize]);
			}
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值