641. 设计循环双端队列

这个博客介绍了一个名为MyCircularDeque的数据结构实现,它是一个环形双端队列。该数据结构支持在队列前端插入和删除元素,以及在队列后端插入和删除元素,并提供了获取队列前端和后端元素的方法。博客详细说明了每个操作的逻辑,包括判断队列是否已满或为空的辅助方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class MyCircularDeque {
    int size = 0;
    int[] nums;
    int start = 0;
    int end = -1;

    /** Initialize your data structure here. Set the size of the deque to be k. */
    public MyCircularDeque(int k) {
        nums = new int[k];
    }

    /** Adds an item at the front of Deque. Return true if the operation is successful. */
    public boolean insertFront(int value) {
        if (isFull()) return false;

        if (isEmpty()) {
            start = 0;
            end = 0;
        } else {
            start = (start == 0 ? nums.length - 1 : start - 1);
        }
        
        nums[start] = value;
        size++;
        return true;
    }

    /** Adds an item at the rear of Deque. Return true if the operation is successful. */
    public boolean insertLast(int value) {
        if (isFull()) return false;

        end = (end + 1) % nums.length;
        nums[end] = value;
        size++;
        return true;
    }

    /** Deletes an item from the front of Deque. Return true if the operation is successful. */
    public boolean deleteFront() {
        if (isEmpty()) return false;

        start = (start + 1) % nums.length;
        size--;
        return true;
    }

    /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
    public boolean deleteLast() {
        if (isEmpty()) return false;

        end = (end == 0 ? nums.length-1 : end-1);
        size--;
        return true;
    }

    /** Get the front item from the deque. */
    public int getFront() {
        return isEmpty() ? -1 : nums[start];
    }

    /** Get the last item from the deque. */
    public int getRear() {
        return isEmpty() ? -1 : nums[end];
    }

    /** Checks whether the circular deque is empty or not. */
    public boolean isEmpty() {
        return size == 0;
    }

    /** Checks whether the circular deque is full or not. */
    public boolean isFull() {
        return size == nums.length;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值