Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".

One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.

Your implementation should support following operations:

  • MyCircularQueue(k): Constructor, set the size of the queue to be k.
  • Front: Get the front item from the queue. If the queue is empty, return -1.
  • Rear: Get the last item from the queue. If the queue is empty, return -1.
  • enQueue(value): Insert an element into the circular queue. Return true if the operation is successful.
  • deQueue(): Delete an element from the circular queue. Return true if the operation is successful.
  • isEmpty(): Checks whether the circular queue is empty or not.
  • isFull(): Checks whether the circular queue is full or not.

Example:

MyCircularQueue circularQueue = new MyCircularQueue(3); // set the size to be 3
circularQueue.enQueue(1);  // return true
circularQueue.enQueue(2);  // return true
circularQueue.enQueue(3);  // return true
circularQueue.enQueue(4);  // return false, the queue is full
circularQueue.Rear();  // return 3
circularQueue.isFull();  // return true
circularQueue.deQueue();  // return true
circularQueue.enQueue(4);  // return true
circularQueue.Rear();  // return 4

Note:

  • All values will be in the range of [0, 1000].
  • The number of operations will be in the range of [1, 1000].
  • Please do not use the built-in Queue library.

设计一个环形队列,包含以下几个操作功能:设置队列大小,获取前一个元素,获取最后一个元素,插入一个元素,删除一个元素,判断队列是否满了,判断队列是否为空。不能用内置的Queue函数库。

解法:数组

Java:

class MyCircularQueue {
final int[] a;
int front, rear = -1, len = 0; public MyCircularQueue(int k) { a = new int[k];} public boolean enQueue(int val) {
if (!isFull()) {
rear = (rear + 1) % a.length;
a[rear] = val;
len++;
return true;
} else return false;
} public boolean deQueue() {
if (!isEmpty()) {
front = (front + 1) % a.length;
len--;
return true;
} else return false;
} public int Front() { return isEmpty() ? -1 : a[front];} public int Rear() {return isEmpty() ? -1 : a[rear];} public boolean isEmpty() { return len == 0;} public boolean isFull() { return len == a.length;}
}  

Python:

class Node:
def __init__(self, value):
self.val = value
self.next = self.pre = None
class MyCircularQueue: def __init__(self, k):
self.size = k
self.curSize = 0
self.head = self.tail = Node(-1)
self.head.next = self.tail
self.tail.pre = self.head def enQueue(self, value):
if self.curSize < self.size:
node = Node(value)
node.pre = self.tail.pre
node.next = self.tail
node.pre.next = node.next.pre = node
self.curSize += 1
return True
return False def deQueue(self):
if self.curSize > 0:
node = self.head.next
node.pre.next = node.next
node.next.pre = node.pre
self.curSize -= 1
return True
return False def Front(self):
return self.head.next.val def Rear(self):
return self.tail.pre.val def isEmpty(self):
return self.curSize == 0 def isFull(self):
return self.curSize == self.size  

C++:

class MyCircularQueue {
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
data.resize(k);
head = 0;
tail = 0;
reset = true;
} /** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value) {
if (isFull()) return false;
// update the reset value when first enqueue happens
if (head == tail && reset) reset = false;
data[tail] = value;
tail = (tail + 1) % data.size();
return true;
} /** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
if (isEmpty()) return false;
head = (head + 1) % data.size();
// update the reset value when last dequeue happens
if (head == tail && !reset) reset = true;
return true;
} /** Get the front item from the queue. */
int Front() {
if (isEmpty()) return -1;
return data[head];
} /** Get the last item from the queue. */
int Rear() {
if (isEmpty()) return -1;
return data[(tail + data.size() - 1) % data.size()];
} /** Checks whether the circular queue is empty or not. */
bool isEmpty() {
if (tail == head && reset) return true;
return false;
} /** Checks whether the circular queue is full or not. */
bool isFull() {
if (tail == head && !reset) return true;
return false;
}
private:
vector<int> data;
int head;
int tail;
// reset is the mark when the queue is empty
// to differentiate from queue is full
// because in both conditions (tail == head) stands
bool reset;
}; /**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue obj = new MyCircularQueue(k);
* bool param_1 = obj.enQueue(value);
* bool param_2 = obj.deQueue();
* int param_3 = obj.Front();
* int param_4 = obj.Rear();
* bool param_5 = obj.isEmpty();
* bool param_6 = obj.isFull();
*/

类似题目:

[LeetCode] 641.Design Circular Deque 设计环形双向队列  

All LeetCode Questions List 题目汇总

[LeetCode] 622.Design Circular Queue 设计环形队列的更多相关文章

  1. [LeetCode] Design Circular Queue 设计环形队列

    Design your implementation of the circular queue. The circular queue is a linear data structure in w ...

  2. [LeetCode] 641.Design Circular Deque 设计环形双向队列

    Design your implementation of the circular double-ended queue (deque). Your implementation should su ...

  3. Leetcode622.Design Circular Queue设计循环队列

    设计你的循环队列实现. 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环.它也被称为"环形缓冲器". 循环队列的一个好处是 ...

  4. LeetCode 622. Design Circular Queue

    原题链接在这里:https://leetcode.com/problems/design-circular-queue/ 题目: Design your implementation of the c ...

  5. [LeetCode] Design Circular Deque 设计环形双向队列

    Design your implementation of the circular double-ended queue (deque). Your implementation should su ...

  6. 【LeetCode】622. Design Circular Queue 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 用直的代替弯的 数组循环利用 日期 题目地址:htt ...

  7. 【leetcode】622. Design Circular Queue

    题目如下: Design your implementation of the circular queue. The circular queue is a linear data structur ...

  8. LeetCode 622:设计循环队列 Design Circular Queue

    LeetCode 622:设计循环队列 Design Circular Queue 首先来看看队列这种数据结构: 队列:先入先出的数据结构 在 FIFO 数据结构中,将首先处理添加到队列中的第一个元素 ...

  9. LeetCode 641. Design Circular Deque

    原题链接在这里:https://leetcode.com/problems/design-circular-deque/ 题目: Design your implementation of the c ...

随机推荐

  1. 201671030104 邓海祥 实验十四 团队项目评审&课程项目总结

    项目 内容 课程名称 2016级计算机科学与工程学院软件工程(西北师范大学) 这个作业的要求在哪里 实验十四 团队项目评审&课程学习总结 课程学习目标 (1)掌握软件项目评审会流程:(2)反思 ...

  2. 利用requests库访问网站

    1.关于requests库 函数 Response对象包含服务器返回的所有信息,也包含请求的Request信息. 访问百度二十次 import requests def getHTMLText(url ...

  3. Nested List Weight Sum

    Description Given a nested list of integers, return the sum of all integers in the list weighted by ...

  4. Frightful Formula Gym - 101480F (待定系数法)

    Problem F: Frightful Formula \[ Time Limit: 10 s \quad Memory Limit: 512 MiB \] 题意 题意就是存在一个\(n*n\)的矩 ...

  5. Vuejs组件基础

    一.概念 ①组件就是对局部视图的封装,组件思想就是把一个很大的复杂的 Web 页面视图给拆分成一块一块的组件视图,然后利用某种特定的方式把它们组织到一起完成完整的 Web 应用构建. ②目前主流的前端 ...

  6. 网卡可以绑定cpu提高吞吐量

    请看大神帖子:https://blog.csdn.net/nawenqiang/article/details/82854929 需要做什么呢? 首先,确认你是否运行irqbalance,这个是nic ...

  7. MyBatis试题

    在使用MyBatis的时候,除了可以使用@Param注解来实现多参数入参,还可以用()传递多个参数值. (选择一项) A.用Map对象可以实现传递多参数值 B.用List对象可以实现传递多参数值 C. ...

  8. 菜鸟网络Java面试-社招-一面(2019/11)

    个人情况 2017年毕业,普通本科,计算机科学与技术专业,毕业后在一个二三线小城市从事Java开发,2年Java开发经验.做过分布式开发,没有高并发的处理经验,平时做To G的项目居多.写下面经是希望 ...

  9. shell 空语句

    在shell脚本中“:”是空命令,表示什么都不做类似于python中的pass

  10. 重置GPU显存 Reset GPU memory after CUDA errors

    Sometimes CUDA program crashed during execution, before memory was flushed. As a result, device memo ...