Use arrays to implement simple queues

//队列是一个有序列表 遵循先入先出原则


//使用数组来模拟队列
public class ArrayQueue {

    class ArrayQ{
        private int maxSize; //队列最大容量
        private int front; //队列头
        private int rear;  //队列尾
        private int arr[]; //数组用于存放数据,模拟队列

        //队列初始化
        public ArrayQ(int arrMaxSize){
            maxSize=arrMaxSize;
            rear=-1;  // 指向队列尾部
            front=-1;  //指向队列前一个位置
            arr=new int[maxSize];
        }
        //判断队列是否满
        public boolean isFull(){
            return rear == maxSize -1;
        }

        // 判断队列是否为空
        public boolean isEmpty(){
            return front == rear;
        }

        //向队列中添加数据
        public void addQueue(int i){
            //判断队列是否已满
            if (isFull()){
                throw new RuntimeException("队列已满,无法添加数据");
            }
            //队列尾部后移一位
            rear++;
            arr[rear]=i;
        }
        //获取队列数据
        public int getQueue(){
            //判断队列是否为空
            if (isEmpty()){
                throw new RuntimeException("队列为空,获取不到数据");
            }
            front++; //队列头部后移一位
            return arr[front];
        }
        //遍历查看当前队列数据
        public void showQueue(){
            if (isEmpty()){
                throw new RuntimeException("队列空");
            }
            for (int i=0;i<arr.length;i++) {
                System.out.println("arr"+"["+i+"]"+arr[i]+"\t");
            }
        }
        //获取队列头数据
        public int headQueue(){
            if(isEmpty()){
                throw new RuntimeException("队列为空,获取不到头数据");
            }
            return arr[front+1];
        }
    }
}

 

Guess you like

Origin blog.csdn.net/qq_41556688/article/details/112593608