02.数组模拟环形队列


/**
 * 环形队列
 */
public class ArrayQueueDemo {
    public static void main(String[] args){
        ArrayQueue queue = new ArrayQueue(3);
        queue.add(1);
        queue.show();
        queue.add(2);
        queue.add(3);
        queue.show();
        System.out.println("queue.getHead() = " + queue.getHead());
        queue.remove();
        System.out.println("queue.getHead() = " + queue.getHead());
        queue.show();
        queue.add(4);
        queue.show();
    }
    //arr[0]=1
    //------
    //队列满了
    //arr[0]=1
    //arr[1]=2
    //------
    //queue.getHead() = 1
    //queue.getHead() = 2
    //arr[1]=2
    //------
    //arr[1]=2
    //arr[2]=4
    //------
}
class ArrayQueue{
    private int[] arr;
    private int maxSize;//数组的最大容量,可存放元素为maxSize-1
    private int front = 0;//队列头,队列的第一个元素
    private int rear = 0;//队列尾,队列的最后一个元素的下一个位置

    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
    }
    //队列是否满了
    public boolean isFull(){
        return (this.rear+1)%maxSize == this.front;
    }
    //队列是否为空
    public boolean isEmpty(){
        return this.rear == this.front;
    }
    public void add(int n){
        if (isFull()){
            System.out.println("队列满了");
            return;
        }
        arr[rear] = n;
        rear = (rear+1) % maxSize;
    }
    public int remove(){
        if (isEmpty()){
            System.out.println("队列为空");
            return -1;
        }
        int i = arr[front];
        front = (front+1) % maxSize;
        return i;
    }
    public void show(){
        // 1 2 3 4 5
        // f     r
        for (int i = front; i < front+size(); i++) {
            System.out.printf("arr[%d]=%d
",i % maxSize,arr[i % maxSize]);
        }
        System.out.println("------");
    }
    public int getHead(){
        if (isEmpty()){
            throw new RuntimeException("队列为空");
        }
        return arr[front];
    }
    private int size(){
        return (maxSize - front + rear) % maxSize;
    }
}
原文地址:https://www.cnblogs.com/fly-book/p/11630299.html