【思想简述】 定义存储数组和队头、队尾指针和已经入队中元素个数,做好队满和队空判断条件。这里queueSize可以使用rear和front关系进行替换。
队列基础类:
- public class queueByArray {
- //初识储存空间和队头、堆尾指针
- Integer[] arr;
- Integer front;
- Integer rear;
- Integer queueSize;
-
- public queueByArray(Integer initSize){
- if(initSize < 0){
- throw new IllegalArgumentException("初始化大小小于零");
- }
- arr = new Integer[initSize];
- front = rear = queueSize = 0;
- }
-
- //判断队是否为空
- public boolean isEmpty(){
- return queueSize==0 ? true : false;
- }
- //判断队是否满
- public boolean isFull(){
- return (queueSize == arr.length-1) ? true : false;
- }
- //进队
- public void inQueue(Integer num){
- //队满
- if(this.isFull()) {
- throw new IllegalArgumentException("队列已满!");
- }
-
- arr[rear] = num;
- rear = rear == arr.length-1 ? 0 : rear +1; //当队列不满,rear后移越界时,返回起点
- queueSize++;
-
- }
- //出队
- public Integer outQueue(){
- //队空
- if(this.isEmpty()){
- throw new IllegalArgumentException("队列为空!");
- }
- Integer tem = arr[front];
- front = front == arr.length-1 ? 0 : front+1;
- queueSize--;
- return tem;
- }
- }
测试类:
- public class queueByArrayTest {
- public static void main(String[] args){
- queueByArray queue = new queueByArray(6);
- System.out.println(queue.isEmpty()); //true
-
- queue.inQueue(3);
- queue.inQueue(4);
- queue.inQueue(6);
- queue.inQueue(9);
- queue.inQueue(7);
-
- System.out.println(queue.isEmpty()); //false
- queue.inQueue(13);
- try {
- queue.inQueue(14); //队满
- }catch (Exception e){
- System.out.println(e);
- }
-
- while(!queue.isEmpty()){
- System.out.println(queue.outQueue()); //3,4,6,9,7
- }
-
- try {
- System.out.println(queue.outQueue()); //"队列为空"
-
- }catch (Exception e){
- System.out.println(e);
- }
-
- queue.inQueue(15);
- queue.inQueue(16);
- queue.inQueue(17);
-
- System.out.println(queue.front); //该处属性应该封装,当前为测试
- System.out.println(queue.rear); //该处属性应该封装
-
-
- }
-
- }