队列_数组实现

队头因为删除的时候需要移动,队尾因为增加的时候需要移动,所以队头的位置相比较于队尾在低下标处。

public class Queue {
    private long[] queArray;
    private int maxSize;
    private int front;
    private int rear;
    private int nItem;//当前队列的数据个数
    public Queue(int s) {
        maxSize=s;
        queArray=new long[maxSize];
        front=0;//因为会有查看队头数据的方法,即select(front),如果队头标志从-1开始,当front是初始状态时,用这个方法就会报错,数组下标不能是负数,所以必须从0开始。
        rear=-1;
        nItem=0;
    }
    //插入
    public void insert(long j) {
        if(rear==maxSize-1)
            rear=-1;//当队列中到尾部满了时,从开始状态开始
        queArray[++rear]=j;
        nItem++;
    }
    //删除
    public  long remove() {
        long temp=queArray[front++];
        if(front==maxSize)
            front=0;//当删到数组的界限时,从初始状态又重新开始。
        nItem--;
        return temp;
    }
    //查看
    public long peekFront() {
        return queArray[front];
    }
    //是否为空
    public  boolean isEmpty() {
        return nItem==0;
    }
    //是否是满的
    public boolean isFull() {
        return nItem==maxSize;
    }
    //当前数据总量
    public int size() {
        return nItem;
    }

}
public class Test {

    public static void main(String[] args) {
        Queue theQueue=new Queue(5);
        theQueue.insert(10);
        theQueue.insert(20);
        theQueue.insert(30);
        theQueue.insert(40);
        System.out.println("remove:"+theQueue.remove());
        System.out.println("remove:"+theQueue.remove());
        System.out.println("remove:"+theQueue.remove());
        theQueue.insert(50);
        theQueue.insert(60);
        theQueue.insert(70);
        theQueue.insert(80);
        //删光
        while(!theQueue.isEmpty()) {
            long n=theQueue.remove();
            System.out.print(n+" ");
        }
        

    }

}
原文地址:https://www.cnblogs.com/S-Mustard/p/8084869.html