leetcode641设计循环双端队列

链接: link.
这个里面是循环单向队列,由于实现的时候使用的是数组,所以单双向没差,拿单向的改一下就行了。

使用的还是空闲单元法,所以注意点还是一样

front : 指向队列中第一个元素
rear : 指向队列中最后一个元素的下一个位置,这个地方注意!!!

在这里插入图片描述
所有减都要有+length
所有加都要有%length
思路:

  1. 队空条件:front == rear;
  2. 队满条件:front == (rear+1)%length;
  3. 队列长度:queue_l = (rear - front +length)%length;
  4. 队头元素:queue[front];
  5. 队尾元素:queue[(rear-1+length)%length];
  6. 队尾插入元素:queue[rear]=value; rear = (rear+1)%length;
  7. 队尾删除元素:rear = (rear -1 +length)%length;
  8. 队首删除元素:front = (front+1)%length;
  9. 队首插入元素:front = (front -1 +lengtj)%length; queue[front] = value;

代码

class MyCircularDeque {
private:
   int *queue = nullptr;
   int front = 0;
   int rear = 0;
   int length = 0;
public:
   /** Initialize your data structure here. Set the size of the deque to be k. */
   MyCircularDeque(int k) {
       queue = (int*)malloc((k+1)*sizeof(int));
       front = 0;
       rear = 0;
       length = k+1;
   }
   
   /** Adds an item at the front of Deque. Return true if the operation is successful. */
   bool insertFront(int value) {
       if(isFull())
           return false;
       front = (front - 1 +length)%length;
       queue[front] = value;
       return true;
   }
   
   /** Adds an item at the rear of Deque. Return true if the operation is successful. */
   bool insertLast(int value) {
       if(isFull())
           return false;
       queue[rear] = value;
       rear = (rear+1)%length;
       return true;

   }
   
   /** Deletes an item from the front of Deque. Return true if the operation is successful. */
   bool deleteFront() {
       if(isEmpty())
           return false;
       front = (front+1)%length;
       return true;
   }
   
   /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
   bool deleteLast() {
       if(isEmpty())
           return false;
       rear = (rear-1+length)%length;
       return true;

   }
   
   /** Get the front item from the deque. */
   int getFront() {
       if(isEmpty())
           return -1;
       return queue[front];
   }
   
   /** Get the last item from the deque. */
   int getRear() {
       if(isEmpty())
           return -1;
       return queue[(rear-1+length)%length];
   }
   
   /** Checks whether the circular deque is empty or not. */
   bool isEmpty() {
       if(front == rear)
           return true;
       return false;
   }
   
   /** Checks whether the circular deque is full or not. */
   bool isFull() {
       if(front == (rear+1)%length)
           return true;
       return false;
   }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值