数组实现队列,此时的队列只能使用一次,下一篇文章,将使用循环数组来实现队列
虽然只有代码,但是注释很详细,如有问题,欢迎评论留言,指点。
package com.atguigu.queue;
import java.util.Scanner;
/**
* @Description 使用数组模拟队列
* @Author Flag
* @Date: 2021/7/3 20:03
* @Version: 1.0
**/
public class ArrqyQueueDome {
public static void main(String[] args) {
//创建一个队列
ArrayQueue arrayQueue = new ArrayQueue(3);
//接收用户输入
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("a(add):添加数据到队列");
System.out.println("g(get):从队列取出数据");
System.out.println("h(head):查看队列头的数据");
key = scanner.next().charAt(0);
switch (key){
case 's':
arrayQueue.showQueue();
break;
case 'a':
System.out.println("请输入一个数:");
int value = scanner.nextInt();
arrayQueue.addQueue(value);
break;
case 'g': //取出数据
try {
int res = arrayQueue.getQueue();
System.out.printf("取出数据是%d\n",res);
} catch (Exception e) {
System.out.printf(e.getMessage());
}
break;
case 'h': //查看队列头的数据
try {
int res = arrayQueue.headQueue();
System.out.printf("队列头的数据是%d\n",res);
} catch (Exception e) {
System.out.printf(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
System.out.println("程序退出");
break;
default:
break;
}
}
}
}
/**
* 使用数据模拟队列-编写一个ArrayQueue类
*/
class ArrayQueue{
private int maxSize;//表示数组的最大容量
private int front;//队列头
private int rear;//队列尾
private int[] arr;//该数据用于用于存储数据,模拟队列
/**
* 创建队列的构造器
* @param maxSize
* @param front
* @param rear
* @param arr
*/
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
this.front = -1; //指向队列头部,分析出这个front是指向队列头的前一个位置
this.rear = -1; //指向队列尾,直接指向队列尾的具体数据,即就是队列最后一个数据
this.arr = new int[this.maxSize];
}
/**
* 判断队列是否已满
* @return
*/
public boolean isFull(){
return rear == maxSize -1 ;
}
/**
* 判断队列是否为null
* @return
*/
public boolean isEmpty(){
return rear == front;
}
/**
* 添加数据到队列
* @param n
*/
public void addQueue(int n){
//判断队列是否已满
if(isFull()){
System.out.println("队列满,不能加入数据");
return;
}
//让rear后移动
rear++;
//将数据添加rear上
arr[rear] = n;
}
/**
* 从队列中获取数据
* @return
*/
public int getQueue(){
//判断队列是否空
if(isEmpty()){
throw new RuntimeException("队列中没有数据,不能取出");
}
//将front向后移动
front = arr[front+1];
//返回front之前的数据
return arr[front];
}
/**
* 显示队列的所有数据
*/
public void showQueue(){
if(isEmpty()){
System.out.println("队列为null,不能打印");
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d]=%d\n",i,arr[i]);
}
}
/**
* 显示队列的头数据,注意不是取出数据
* @return
*/
public int headQueue(){
if(isEmpty()){
throw new RuntimeException("队列为null,没有头部数据");
}
//font指向队列头的前一个数据,所以需要加一
return arr[front+1];
}
}