package com.hao.firstdemo.datastruct;
/**
* @author haoxiansheng
*/
public class TestCircleArry {
public static void main(String[] args) {
//测试代码自己可以实现
CircleArray circleArray = new CircleArray(7);
circleArray.addQueue(5);
circleArray.show();
}
}
class CircleArray {
private int maxSize; //表示数组的最大容量
/**
* 指向队列的第一个元素,也就是说arr[front]就是队列的第一个元素 初始值 front = 0
* 队列头部
*/
private int front;
/**
* 指向最后一个元素的后一个位置,希望空出一个空间做约定。初始值 rear = 0
* 队列尾部
*/
private int rear;
private int[] arr; //存放数据
/**
* 创建队列构造器
* front rear 默认为0
*
* @param arryMaxSize
*/
public CircleArray(int arryMaxSize) {
maxSize = arryMaxSize;
arr = new int[maxSize];
}
/**
* 判断队列是否满了
*
* @return
*/
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
/**
* 判断队列是否为空
*
* @return
*/
public boolean isEmpty() {
return rear == front;
}
/**
* 添加数据
*
* @param n
*/
public void addQueue(int n) {
if (isFull()) {
System.out.println("队列已满不能添加数据");
return;
}
//添加数据
arr[rear] = n;
//指针后移 取模
rear = (rear + 1) % maxSize;
}
/**
* 获取队列数据 出队
*
* @return
*/
public int popQueue() {
if (isEmpty()) {
System.out.println("队列中不存在数据");
throw new RuntimeException("队列为空,不能取数据");
}
/**
* 1、先将数据保存到一个零时变量中
* 2、front 后移
* 3、将零时变量返回
*/
int temp = arr[front];
front = (front + 1) % maxSize;
return temp;
}
/**
* 显示数据
*/
public void show() {
if (isEmpty()) {
System.out.println("队列中没有数据");
}
for (int i = front; i < front + size(); i++) {
System.out.printf("arr[%d]=%d", i % maxSize, arr[i % maxSize]);
}
}
/**
* 求出队列中数据的有效个数
*
* @return
*/
public int size() {
return (rear + maxSize - front) % maxSize;
}
/**
* 显示队列的头数据
*
* @return
*/
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列空的没有数据");
}
return arr[front];
}
}