Leetcode每日一题练习 ------ 641. 设计循环双端队列

Leetcode 每日一题练习继续讨论:

641. 设计循环双端队列
641. Design Circular Deque

题解

本题是中等难度题,但题目本身逻辑比较简单,要实现双端循环链表,只需记录下链表的首部和尾部位置信息,链表的当前大小和最大容量按要求实现即可。可以用数组也可以用链表,本题中我使用数组实现。

代码


class MyCircularDeque {
private:
    vector<int> data;
    int front;
    int rear;
    int size;
    int capacity;

public:
    MyCircularDeque(int k) : data(k), front(0), rear(0), size(0), capacity(k) {}
    
    bool insertFront(int value) {
        if (isFull()) return false;
        data[front] = value;
        if(size == 0){
            rear = (front+1)%capacity;
        }
        front = (front - 1 + capacity) % capacity;
        size++;
        return true;
    }
    
    bool insertLast(int value) {
        if (isFull()) return false;
        data[rear] = value;
        if (size == 0){
            front = (rear - 1 + capacity) % capacity;
        }
        rear = (rear + 1) % capacity;
        size++;
        return true;
    }
    
    bool deleteFront() {
        if (isEmpty()) return false;
        front = (front + 1) % capacity;
        size--;
        return true;
    }
    
    bool deleteLast() {
        if (isEmpty()) return false;
        rear = (rear - 1 + capacity) % capacity;
        size--;
        return true;
    }
    
    int getFront() {
        if (isEmpty()) return -1;
        return data[(front+1)%capacity];
    }
    
    int getRear() {
        if (isEmpty()) return -1;
        return data[(rear - 1 + capacity) % capacity];
    }
    
    bool isEmpty() {
        return size == 0;
    }
    
    bool isFull() {
        return size == capacity;
    }
};

1 个赞

感谢你的分享!

2 个赞

刷题佬!来了!

1 个赞