1、java数组实现环形队列
队列先进先出
import java.util.Scanner;
public class CircleQueueDemo {
public static void main(String[] args) {
CircleQueue queue=new CircleQueue(4);
char key=' ';
Scanner scanner=new Scanner(System.in);
boolean loop=true;
while (loop){
System.out.println("s(show):显示队列");
System.out.println("e(exit):退出程序");
System.out.println("g(get):从队列取出数据");
System.out.println("a(add):添加数据");
System.out.println("h(head):查看队列头的信息");
key=scanner.next().charAt(0);
switch (key){
case 's':
queue.showQuence();
break;
case 'e':
scanner.close();
loop=false;
break;
case 'a':
System.out.println("请输入一个数");
int value=scanner.nextInt();
queue.addQuence(value);
break;
case 'g':
try{
int index= queue.getQuence();
System.out.printf("g(get):从队列取出数据%d\n",index);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'h':
try{
int index= queue.getQuence();
System.out.printf("h(head):查看队列头的信息%d\n",index);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
}
}
}
}
class CircleQueue{
//数组的长度
private int maxSize;
//指向第一个元素,起始位置
private int front;
//指向最后一个元素的后一个位置
private int rear;
private int[] arr;
public CircleQueue(int arrMaxSize){
maxSize=arrMaxSize;
arr=new int[maxSize];
front=0;
rear=0;
}
public boolean isFull(){
return (rear+1)%maxSize==front;
}
public boolean isEmpty(){
return rear==front;
}
public void addQuence(int n){
if(isFull()){
System.out.println("队列满");
return;
}
arr[rear]=n;
rear=(rear+1)%maxSize;
}
public int getQuence(){
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+1];
}
public void showQuence(){
if (isEmpty()) {
System.out.println("数据为空");
return;
}
for(int i=front;i
System.out.printf("arr[%d]=%d\n",i%maxSize,arr[i%maxSize]);
}
}
public int size(){
return (maxSize+rear-front)%maxSize;
}
}