为解决刚才队列的问题,引入循环队列来解决问题。
1.循环队列设计思路
- 预留一个空间作为约定,也就是说队列的最大容量变为了maxSize-1了
- front指针做tfron调整:front指向队中的头元素,初始值为front=0
- rear指针做调整:rear指向队列中最后一个元素的后一个元素,因为想空出一个空间作为元素,初始值为rear=0
- 队空判断条件:front==rear
- 队满判断条件:(rear+1)%maxSize == front
- 队中元素个数:(rear+maxSize-front)%maxSize
2.代码实现
package com.yc.day01.queue;
import java.util.Scanner;
public class LoopQueueTest {
public static void main(String[] args) {
LoopQueue queue = new LoopQueue(3);
Scanner scanner = new Scanner(System.in);
char key = ' ';
boolean loop = true;
while (loop){
System.out.println("s(show):显示队列中所有元素");
System.out.println("a(add):添加一个元素");
System.out.println("p(pop):取出一个元素");
System.out.println("g(getHead):获取头元素");
System.out.println("l(length):获取队列长度");
System.out.println("e(exit):退出");
key = scanner.next().charAt(0);
switch (key){
case 's':
queue.print();
break;
case 'a':
System.out.println("请输入一个数:");
int value = scanner.nextInt();
try{
queue.add(value);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'p':
try{
int pop = queue.pop();
System.out.println("取出的元素为:"+pop);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'g':
try{
int head = queue.getHead();
System.out.println("头元素为:"+head);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'l':
int length = queue.length();
System.out.println("队列元素个数为:"+length);
break;
case 'e':
loop = false;
scanner.close();
break;
default:
break;
}
}
}
}
class LoopQueue{
private int maxSize;
private int front;
private int rear;
private int[] arr;
public LoopQueue(int maxSize){
this.maxSize = maxSize;
this.arr = new int[maxSize];
this.front = 0;
this.rear = 0;
}
public boolean isFull(){
return (rear+1)%maxSize==front;
}
public boolean isEmpty(){
return rear==front;
}
public void add(int i){
if(isFull()){
throw new RuntimeException("队列已满");
}
arr[rear] = i;
rear = (rear+1)%maxSize;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("队列为空");
}
int value = arr[front];
front = (front+1)%maxSize;
return value;
}
public int getHead(){
if(isEmpty()){
throw new RuntimeException("队列为空");
}
return arr[front];
}
public int length(){
return (rear+maxSize-front)%maxSize;
}
public void print(){
for (int i = front; i < front+length(); i++) {
System.out.printf("arr[%d]=%d\n",i%maxSize,arr[i%maxSize]);
}
}
}