分析
说明: tail :表示队列的最后一个元素,head表示队列的第一个元素,初始值都设置为-1
1.什么时候表示队列为空?
当tail==head表示队列对空
2.什么时候队列为满呢?
(tail+队列的长度-head+1)%队列的长度 == 0表示队列为满
3.队列中的有效个数?
(tail+队列的长度-head+1)%队列的长度 == 0 ?队列的长度:(tail+队列的长度-head+1)%队列的长度
代码实现
package com.zyp;
import java.util.Scanner;
/**
* 数组模型,环形队列实现
*
*/public class App
{
public static void main( String[] args ) {
CircleArray circleArray = new CircleArray(8);
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println("请选择:a(表示添加元素);" +
"p(表示取出元素);"+
"q(表示遍历元素)");
String next = scanner.next();
switch (next){
case "a":
System.out.println("请添加一个元素:");
int i = scanner.nextInt();
if(circleArray.isFull()){
System.out.println("该队列已满");
return;
}
circleArray.add(i);
circleArray.queryArray();
break;
case "p":
if(circleArray.isEmpty()){
System.out.println("该队列已空");
return;
}
int pull = circleArray.pull();
System.out.println("取出得元素为:"+pull);
circleArray.queryArray();
break;
case "q":
circleArray.queryArray();
break;
}
}
}
}
class CircleArray{
private int[] array;
//代表第一个元素,初始化为-1
private int head;
//表示最后一个元素,初始化为-1
private int trailer;
CircleArray(int size){
array = new int[size];
head = -1;
trailer = -1;
}
/**
* 判断是否为已满的状态
* @return
*/ public boolean isFull(){
if((trailer+array.length+1- head)%array.length == 0){
return true;
}
return false;
}
/**
* 判断是否为空
* @return
*/ public boolean isEmpty(){
if(trailer == head){
return true;
}
return false;
}
/**
* 添加元素
* @param element
*/ public void add(int element){
if(isFull()){
throw new Runtime Exception ("队列已满,无法再次添加元素");
}
trailer = (trailer+1)%array.length;
if(head == -1){
head = (head+1)%array.length;
}
array[trailer] = element;
}
/**
* 取出元素
* @return
*/ public int pull(){
if(isEmpty()){
throw new RuntimeException("队列种不存在元素");
}
int firstElementIndex = head;
head = (head + 1)%array.length;
return array[firstElementIndex];
}
/**
* 查询队列元素
*/ public void queryArray(){
System.out.println("队列种的元素为:");
for(int i = head;i<head+size();i++){
System.out.print("t"+array[i%array.length]);
}
System.out.println();
}
/**
* 有效个数
* @return
*/ public int size(){
return (trailer+array.length - head+1)%array.length == 0?array.length:(trailer+array.length - head+1)%array.length;
}
}