循环队列
- 定义:优化的简单队列,通过取模的形式,可将队列看作是一个循环,这样可以实现数组的复用
- 分析
- 队空的条件:rear==font
- 队满的条件:因为是循环队列,队满的条件有所改变,当满足(rear+1)%maxSize == font,队列未满,小伙伴们可以自行带入数据检验
- 分许图
- 初始条件调整:初始时font便指向队列第一个位置,既font = 0,同时rear = 1
- 代码实现
package com.xc.queue;
import java.util.Scanner;
class test{
public static void main(String[] args) {
CircleQueue circleQueue = new CircleQueue(4);
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("-------------1-入队--------------");
System.out.println("-------------2-出队--------------");
System.out.println("-------------3-队首元素-----------");
System.out.println("-------------4-显示队列元素--------");
System.out.println("-------------5-退出---------------");
System.out.print("请选择您的操作:");
int choose = scanner.nextInt();
switch (choose) {
case 1:
System.out.print("请输入一个元素入队:");
int data = scanner.nextInt();
circleQueue.offer(data);
System.out.println("当前队列:");
circleQueue.show();
break;
case 2:
try {
circleQueue.poll();
System.out.println("当前队列:");
circleQueue.show();
} catch (Exception e) {
e.printStackTrace();
}
break;
case 3:
System.out.println("当前队列:");
circleQueue.show();
break;
case 4:
try {
System.out.println(circleQueue.peek());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 5:
System.exit(0);
}
}
}
}
public class CircleQueue {
private int font;
private int rear;
private int maxSize;
private int [] data;
public CircleQueue(int maxSize){
data = new int[maxSize];
this.maxSize = maxSize;
font = 0;
rear = 0;
}
public boolean isEmpty(){
if(font == rear){
return true;
}
return false;
}
public boolean isFull(){
if((rear+1)%maxSize == font){
return true;
}
return false;
}
public void offer(int data){
if(isFull()){
System.out.println("队满无法添加数据");
return ;
}
this.data[rear] = data;
this.rear = (rear+1)%maxSize;
}
public int poll() throws Exception {
if(isEmpty()){
System.out.println("队空,出对失败");
throw new Exception("队列为空");
}
int info = this.data[font];
this.data[font] = 0;
font = (font+1)%maxSize;
return info;
}
public void show(){
if(isEmpty()){
System.out.println("对列中没有数据");
}
for(int i = font;i<font+(rear+maxSize-font)%maxSize;i++){
System.out.println("data"+"["+i+"]"+"="+data[i]);
}
}
public int peek() throws Exception {
if(isEmpty()){
throw new Exception("队列中没有数据");
}
return this.data[font];
}
}