数组模拟队列
【摘要】 package com.itzkx.queue;
import java.util.concurrent.ExecutionException;
public class ArrayQueueDemo { public static void main(String[] args) { }
}
//使用数组模拟队列-编写一个ArrayQueue类
class ArrayQu...
package com.itzkx.queue;
import java.util.concurrent.ExecutionException;
public class ArrayQueueDemo { public static void main(String[] args) { }
}
//使用数组模拟队列-编写一个ArrayQueue类
class ArrayQueue{ private int maxSize; //表示数组的最大容量 private int front; //队列头 private int rear; //队列尾 private int[] arr; //该数组用于存放数据,模拟队列 //创建队列的构造器 public ArrayQueue(int arrMaxSize){ maxSize = arrMaxSize; arr = new int[maxSize]; rear = arr[-1]; front= arr[-1]; } //判断队列是否已满 public boolean isFull(){ return rear==maxSize-1; } //添加元素 public void addQueue(int n){ //先判断队列满了没 if(isFull()){ throw new RuntimeException("队列已满"); } //尾指针+1 rear++; //赋值 arr[rear]=n; } ////判断队列是否为空 public boolean isEmpty(){ return rear==front; } //取出元素 public void showQueue(){ if(isEmpty()){ //通过抛出异常 throw new RuntimeException("队列为空,不可以再取"); } //取出元素 for (int i=0;i<arr.length;i++){ System.out.printf("arr[%d]=%d\n",i,arr[i]); } } //显示队列的头部,不是取出数据 public int headQueue(){ //判断数据是否为空 if(isEmpty()){ //通过抛出异常 throw new RuntimeException("队列为空,不可以再取"); } return arr[front+1]; }
}
文章来源: www.jianshu.com,作者:百忍成金的虚竹,版权归原作者所有,如需转载,请联系作者。
原文链接:www.jianshu.com/p/a0d827f04fd9
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)