2021-12-9 力扣(循环队列)

1. 622 设计循环队列

在这里插入图片描述
answer:
我采用的是牺牲一个数组空间的写法;
int[] nums = new int[k+1];
想象成一个环来模拟;
进队:
nums[rear] = value;
rear = (rear + 1) % maxSize;
出队:
front = (front + 1) % maxSize;

	private int front;
    private int rear;
    private int[] nums;
    private int maxSize;
    public MyCircularQueue(int k) {
        front = 0;
        rear = 0;
        nums = new int[k+1];
        maxSize = k+1;
    }
    
    public boolean enQueue(int value) {
        if (isFull()) 
            return false;
        nums[rear] = value;
        rear = (rear + 1) % maxSize;
        return true;
    }
    
    public boolean deQueue() {
        if (isEmpty()) 
            return false;
        front = (front + 1) % maxSize;
        return true;
    }
    
    public int Front() {
        if (isEmpty())
            return -1;
        return nums[front];
    }
    
    public int Rear() {
        if (isEmpty())
            return -1;
        if (rear == 0)
            return nums[maxSize-1];
        return nums[rear-1];
    }
    
    public boolean isEmpty() {
        return front == rear;
    }
    
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

2. 641设计循环双端队列

在这里插入图片描述
answer:
与上一题类似;
同样牺牲一个数组的空间!
正常情况是front出,rear入;
insertFront();
deleteLast();
getRear();
注意上述三个方法的差别;
insertFront();deleteLast();可以模仿insertLast();deleteFront();来写!

注意赋值和指针移动的先后顺序!
以及front = (front-1+maxSize) % maxSize;

private int front;
    private int rear;
    private int[] nums;
    private int maxSize;
    public MyCircularDeque(int k) {
        front = 0;
        rear = 0;
        nums = new int[k+1];
        maxSize = k+1;
    }
    
    public boolean insertFront(int value) {
        if (isFull())
            return false;
        front = (front-1+maxSize) % maxSize;
        nums[front] = value;
        return true;
    }
    
    public boolean insertLast(int value) {
        if (isFull())
            return false;
        nums[rear] = value;
        rear = (rear + 1) % maxSize;
        return true;
    }
    
    public boolean deleteFront() {
        if (isEmpty())
            return false;
        front = (front + 1) % maxSize;
        return true;
    }
    
    public boolean deleteLast() {
        if (isEmpty())
            return false;
        rear = (rear-1+maxSize) % maxSize;
        return true;
    }
    
    public int getFront() {
        if (isEmpty())
            return -1;
        return nums[front];
    }
    
    public int getRear() {
        if (isEmpty())
            return -1;
        return nums[(rear-1+maxSize) % maxSize];
    }
    
    public boolean isEmpty() {
        return front == rear;
    }
    
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值