实现思路:
-
front 表示指向队列第一个元素,初始化为0。 -
rear 表示指向队列最后一个元素的后一个位置,初始化为0。 -
数组实现环形队列需要预留一个空位置(不放元素)。 -
当队列已满时,满足:(rear + 1) % capacity == front -
当队列为空时,满足:(rear + capacity - front) % capacity == 0 -
当出队列时,front变化满足front = (front + 1) % capacity -
队列元素个数等于(rear + capacity - front) % capacity
完整代码
public class CircleArray {
private int front;
private int rear;
private int capacity;
int []queue;
public CircleArray(){
front = 0;
rear = 0;
capacity = 10;
queue = new int[capacity];
}
public CircleArray(int capacity){
front = 0;
rear = 0;
this.capacity = capacity;
queue = new int[capacity];
}
public boolean isFull(){
return (rear + 1) % capacity == front;
}
public boolean isEmpty(){
return (rear + capacity - front) % capacity == 0;
}
public void queueAdd(int x){
if(isFull()){
throw new RuntimeException("队列已满,不能入队列!");
}
queue[rear] = x;
rear = (rear + 1) % capacity;
}
public int queueFront(){
if(isEmpty()){
throw new RuntimeException("队列为空,无法取数据!");
}
return queue[front];
}
public int queuePop(){
if(isEmpty()){
throw new RuntimeException("队列为空,不能出队列!");
}
int value = queue[front];
front = (front + 1) % capacity;
return value;
}
public int queueSize(){
return (rear + capacity - front) % capacity;
}
public void showQueue(){
if(isEmpty()){
throw new RuntimeException("队列为空,无法显示数据!");
}
int tmp = front;
for(int i = 0; i < queueSize(); i++){
System.out.print(queue[tmp] + " ");
tmp = (tmp + 1) % capacity;
}
}
}
代码测试
测试代码:
class Test01{
public static void main(String[] args) {
CircleArray c = new CircleArray(5);
System.out.println("a:isFull");
System.out.println("b:isEmpty");
System.out.println("c:queueAdd");
System.out.println("d:queueFront");
System.out.println("e:queuePop");
System.out.println("f:queueSize");
System.out.println("g:showQueue");
Scanner scanner = new Scanner(System.in);
while(true){
char k = scanner.next().charAt(0);
switch(k){
case 'a':
System.out.println(c.isFull());
break;
case 'b':
System.out.println(c.isEmpty());
break;
case 'c':
try{
c.queueAdd(scanner.nextInt());
}catch(RuntimeException e){
System.out.println(e.getMessage());
}
break;
case 'd':
try{
System.out.println("对头数据为:" + c.queueFront());
}catch(RuntimeException e){
System.out.println(e.getMessage());
}
break;
case 'e':
try{
System.out.println(c.queuePop() + "已被出队列!");
}catch(RuntimeException e){
System.out.println(e.getMessage());
}
break;
case 'f':
System.out.println(c.queueSize());
break;
case 'g':
try{
c.showQueue();
}catch(RuntimeException e){
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
}
}
|