实现自定义队列

public class MyQueue {
    private int[] array;
    private int front;
    private int rear;

    public MyQueue(int capacity){
        this.array=new int[capacity];
    }
    public void enQueue(int element){
        if((rear+1)%array.length ==front )
            return;//队列已满
        array[rear] = element;
        rear = (rear+1)%array.length;
    }
    //出队
    public int deQueue() throws Exception{
        if(rear == front){throw new Exception("队列一空");}
        int deQueueElement = array[front];
        front=(front+1)%array.length;
        return deQueueElement;
    }
    //输出队列
    public void output(){
        for (int i=front;i!=rear;i=(i+1)%array.length) System.out.println(array[i]);
    }
}

  

posted @ 2024-03-25 17:42  dmfsimle  阅读(3)  评论(0编辑  收藏  举报