简单循环数组实现队列

最近在看数据结构与算法之类的书,看到喜欢的小东西随手记一下。

/**
 * 简单循环数组构造队列结构
 * @author Administrator@2018年12月12日 下午8:30:47
 */
public class ArrayQueue {

	public int capacity;
	public int[] arrayQueue;
	public int front;
	public int rear;
	
	public ArrayQueue(int size) {
		capacity = size;
		arrayQueue = new int[size];
		front = -1;
		rear = -1;
	}
	
	/**
	 * 队列是否为空
	 * @return
	 * @author Administrator@2018年12月12日 下午8:33:59
	 */
	public boolean isEmpty() {
		return (front == -1);
	}
	
	/**
	 * 判断队列是否已经满了
	 * @return
	 * @author Administrator@2018年12月12日 下午8:35:02
	 */
	public boolean isFull() {
		return ((rear + 1)%capacity == front);
	}
	
	/**
	 * 删除队列首元素
	 * @return
	 * @author Administrator@2018年12月12日 下午8:36:33
	 */
	public int arrayPoll() {
		if(isEmpty()) {
			throw new NullPointerException("队列已经空了!");
		}
		int data = arrayQueue[front];
		if(front == rear) {
			front = rear = -1;
		}else {
			front = (front + 1) % capacity;
		}
		return data;
	}
	
	/**
	 * 元素入队
	 * @param element
	 * @return
	 * @author Administrator@2018年12月12日 下午8:37:09
	 */
	public int arrayOffer(int element) {
		if(isFull()) {
			throw new IndexOutOfBoundsException("队列已满!");
		}
		rear = (rear + 1) % capacity;
		arrayQueue[rear] = element;
		if(front == -1) {
			front = rear;
		}
		return arrayQueue[front];
	}
	
	/**
	 * 获取队首元素
	 * @return
	 * @author Administrator@2018年12月12日 下午8:37:53
	 */
	public int arrayPeek() {
		if(isEmpty()) {
			throw new NullPointerException("队列已经空了!");
		}
		return arrayQueue[front];
	}
	
	/**
	 * 获取队列元素的个数
	 * @return
	 * @author Administrator@2018年12月12日 下午8:48:18
	 */
	public int arrayQueueCapicity() {
		return (rear - front + 1 + capacity) % capacity;
	}
	
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值