队列的实现

队列是一种先入先出(FIFO)的数据结构,可以使用数组或者链表实现,入队和出队的时间复杂度为O(1)。

队列的应用在于重演历史。多线程中争夺公平锁的等待队列,按照优先级出队的优先队列等。

循环队列的实现

为了维持队列容量的恒定,可以用数组来实现循环队列,此时队列的容量为数组容量-1。

public class MyQueue {
    //队列使用数组存储,队列的容量为数组容量-1
    private int[] array;
    //队头下标
    private int front;
    //队尾下标,指向最后一个入队元素的下一个位置
    private int rear;

    public MyQueue(int capacity) {
        array = new int[capacity];
    }

    public static void main(String[] args) throws Exception {
        MyQueue myQueue = new MyQueue(5);
        myQueue.enQueue(1);
        myQueue.enQueue(2);
        myQueue.enQueue(3);
        myQueue.enQueue(4);
        myQueue.print();

        System.out.println(myQueue.deQueue());
        System.out.println(myQueue.deQueue());
        System.out.println(myQueue.deQueue());
        System.out.println(myQueue.deQueue());
    }

    public void enQueue(int element) throws Exception {
        if ((rear + 1) % array.length == front) {
            throw new Exception("队列已满");
        }

        array[rear] = element;
        rear = (rear + 1) % array.length;
    }

    public int deQueue() throws Exception {
        if (front == rear) {
            throw new Exception("队列已空");
        }
        int element = array[front];
        front = (front + 1) % array.length;
        return element;
    }

    public void print() {
        //从front到rear,循环打印
        for (int i = front; i != rear; i = (i + 1) % array.length) {
            System.out.print(array[i] + " ");
        }

        System.out.println();
    }
}

队列初始化(入队):1 2 3 4 
出队:1
出队:2
出队:3
出队:4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值