//算法2:环形队列
front指向最前面的元素
rear指向最后一个元素的后一个位置,约定留一个空闲位置
class team{
int maxSize ;
int rear ;
int front ;
int[] arr ;
//构造函数
public team(int size){
maxSize = size;
arr = new int [size];
front = 0;
rear = 0;
}
//添加数据
public void addData(int data){
//先判断数组是否已满
if(isFull()){
System.out.println("数组已满!");
}else{
arr[rear] = data;
rear = (rear+1) % maxSize;
}
}
//判断数组是否已满
public boolean isFull(){
if((rear+1)%maxSize==front){
return true;
}else{
return false;
}
}
//从队列中取数据
public int getData(){
//先判断数组是否为空
if(isEmpty()){
throw new RuntimeException("数组为空");
}
int value = arr[front];
front = (front+1) % maxSize;
return value;
}
//判断数组是否为空
public boolean isEmpty(){
if(rear == front){
return true;
}else{
return false;
}
}
//展示数组数据
public void allData(){
if(isEmpty()){
System.out.println("数组为空");
}else{
for(int i=front;i<front+dataSize();i++){
System.out.printf("arr[%d]=%d\n",i % maxSize,arr[i%maxSize]);
}
}
}
//显示头数据
public void getHead(){
if(isEmpty()){
throw new RuntimeException("数组为空");
}
System.out.println(arr[front]);
}
//获取有效数据的个数
public int dataSize(){
if(isEmpty()){
throw new RuntimeException("数组为空");
}
return (rear+maxSize-front) % maxSize;
}
//控制台测试
public static void main(String[] args) {
team t = new team(4);
Scanner s = new Scanner(System.in);
boolean loop = true;
while (loop){
System.out.println("1:显示所有数据");
System.out.println("2:添加数据");
System.out.println("3:显示头数据");
System.out.println("4:取出数据");
System.out.println("5:退出程序");
int value = s.nextInt();
switch (value){
case 1:
t.allData();
break;
case 2:
System.out.println("请添加数据");
int i = s.nextInt();
t.addData(i);
break;
case 3:
try {
t.getHead();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 4:
try {
System.out.println(t.getData());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 5:
loop = false;
break;
}
}
}
}