数组实现队列
队列基本概念
就如现实中排队吃饭一样,先排队的人先吃饭,后排队的人后吃饭,队列中遵循先进先出的原则
队列示意图
当初始化为:front=-1, rear=-1
rear==maxQueue-1时,队列为满 (maxQueue为数组能存数据的最大个数)
front==rear时,队列为空
代码实现
public class Demo02 {
public static void main(String[] args) {
arrayQueue queue= new arrayQueue(4);
Scanner sc=new Scanner(System.in);
Boolean flat=true; //标志变量
while (flat){
System.out.println("a(在队列中添加数据)");
System.out.println("g(在队列中取出数据)");
System.out.println("h(查看队列中的头部数据)");
System.out.println("s(查看队列中的数据)");
System.out.println("e(退出程序)");
char s=sc.next().charAt(0);
switch (s){
case 'a':{ //用户输入a:在队列中添加数据
System.out.println("请输入要添加的数:");
int value=sc.nextInt();
queue.addQueue(value);
break;
}
case 'g':{ //用户输入g:在队列中取出数据
try{ //try{}catch{}捕获异常
int value=queue.getQueue();
System.out.println("成功取出数据,取出的数据为:"+value);
System.out.println("取出成功!!当前队列为:");
queue.listQueue();
}catch (RuntimeException e){
System.out.println(e.getMessage());
}
break;
}
case 'h':{ //用户输入h:查看队列中的头部数据
try{
int value=queue.headQueue();
System.out.println("当前头部数据为:"+value);
}catch (RuntimeException e){
System.out.println(e.getMessage());
}
break;
}
case 's':{ //用户输入s: 查看队列中的数据
try{
queue.listQueue();
}catch (RuntimeException e){
System.out.println(e.getMessage());
}
break;
}
case 'e':{ //用户输入e: 退出程序
sc.close();
flat=false;
}
}
}
}
//数组形式实现队列
static class arrayQueue{
int maxQueue; //数组的最大容量
int front; //队列头部
int rear; //队列尾部
int [] arr; //数组
public arrayQueue(int maxQueue){
this.maxQueue=maxQueue;
arr=new int[maxQueue];
front=-1; //front表示头部的前一个,即头部数据为arr[front-1]
rear=-1; //rear表示当前尾部数据,即尾部数据为arr[rear]
}
//判断队列是否为满
public Boolean isEmpty(){
return rear==maxQueue-1; //如果尾部达到最大长度则表示队列已经满了,-1则因为数组下标从0开始
}
//判断队列是否空
public Boolean isFull(){
return front==rear; //当头部等于尾部的时候表示队列为空
}
//在队列中添加数据
public void addQueue(int value){
if(isEmpty()){ //判断队列是否已满,满了则不能再添加数据
System.out.println("队列已满,不能添加数据!!!");
return;
}
arr[++rear]=value; //因为rear表示尾部,所以需先+1再进行赋值,否则会覆盖掉尾部的数据
System.out.println("添加成功!!当前队列为:");
listQueue(); //打印队列
}
//从队列中取出数据
public int getQueue(){
if(isFull()){ //判断队列是否为空,为空则无法取出数据
throw new RuntimeException("队列为空,无法取出!!!"); //抛出异常
}
int value=arr[++front];//因为front表示的是头部前一个位置,所以需先+1再取出数据
return value;
}
//查看队列的头部数据
public int headQueue() {
if (isFull()) { //判断队列是否为空,为空则没有头部数据
throw new RuntimeException("队列为空!!!");
}
return arr[front+1];//因为front表示的是头部前一个位置,所以需先+1才能查看数据。!!但因为只是查看头部数据,所以无须改变front的值!!
}
//打印队列
public void listQueue(){
if(isFull()){ //判断队列是否为空,为空无法打印
throw new RuntimeException("队列为空!!!");
}
System.out.println("当前队列为:");
for (int i = front+1; i <=rear; i++) { //front为队列头部的前一个位置,所以front+1才表示队列头部位置,rear表示队列尾部数据
System.out.print(arr[i]+" ");
}
System.out.println();
}
}
}